NSArrayM setObject:atIndex:]: object cannot be nil - ios

Having a little issue with a bit of code, returning the error listed above after running its respective action:
- (IBAction)uploadData:(id)sender {
NSMutableArray *uploadArray = [[NSMutableArray alloc]init];
[uploadArray addObject:#"hire.csv"];
[uploadArray addObject:#"equipment.csv"];
[uploadArray addObject:#"signature.png"];
NSString * docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString * proof1 = [docPath stringByAppendingPathComponent:#"proof1.png"];
if([[NSFileManager defaultManager] fileExistsAtPath: proof1])
{
[uploadArray addObject:#"proof1.png"];
}
NSString * proof2 = [docPath stringByAppendingPathComponent:#"proof2.png"];
if([[NSFileManager defaultManager] fileExistsAtPath: proof2])
{
[uploadArray addObject:#"proof2.png"];
}
NSString * proof3 = [docPath stringByAppendingPathComponent:#"proof3.png"];
if([[NSFileManager defaultManager] fileExistsAtPath: proof3])
{
[uploadArray addObject:#"proof3.png"];
}
int arrayCount = [uploadArray count];
int i = 0;
NSString *arrayString;
for (i = 0; i < arrayCount; i++)
{
uploadArray[i] = arrayString;
if(arrayString != nil)
{
NSString * uploadString = [docPath stringByAppendingPathComponent:arrayString];
[self upload:uploadString ftpUrl:#"ftp.xxxxxxxx.com/xx/xx" ftpUsr:#"xxx" ftpPass:#"xxx"];
}
NSLog(uploadArray[i]);
}
}
Now, if I disable everything in the for loop except for the NSLog() I get no error, and it returns the correct list of objects in the array.
This to me suggests that none of the objects should return nil, surely?
Could anyone help me spot what I'm doing wrong? (probably quite a lot as im pretty new to this stuff)

As your error clearly stats, you are adding a nil object to an array and this is not allowed.
In the below code you have not assigned anything to arrayString making it nil. Then you try to add it to your array.
NSString *arrayString;
for (i = 0; i < arrayCount; i++)
{
uploadArray[i] = arrayString;
From the looks of your code you are trying to add every element form your array to your string. You are doing this the wrong way around. You need a NSMutableString and do something like:
[arrayString appendString: uploadArray[i]];

Related

How to separate NSString with multiple commas?

Am having this nsstring
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
now i want to display only the countries which are suffixed by "en_US".
can anybody tell me how to split that string to get the countries.
I did like this
NSError * error;
NSString* imageName = [[NSBundle mainBundle] pathForResource:#"CountryList" ofType:#"txt"];
NSString * countrStr = [NSString stringWithContentsOfFile:imageName encoding:NSStringEncodingConversionAllowLossy error:&error];
NSArray * dfd = [countrStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<dfd.count;i++)
{
NSString * nama = [dfd objectAtIndex:1];
NSArray * djk = [nama componentsSeparatedByString:#","];
NSString * aksjd = [djk objectAtIndex:1];
}
You can do it like this;
NSString * countryStr = #"6023117,159,en_US,Seychelles,SC,Seychelles,6023185,95,en_US,Kuwait,KW,Kuwait,6023182,172,en_US,Swaziland,SZ,Swaziland,6023185,157,en_US,Saudi Arabia,SA,Saudi Arabia,6023182,177,en_US,Tanzania,TZ,Tanzania,6023185,179,en_US,Togo,TG,Togo,6023185,87,en_US,Cote d'Ivoire,CI,Cote d'Ivoire";
NSArray * arrData = [countryStr componentsSeparatedByString:#","];;//[countryStr componentsSeparatedByString:#"en_US"];
for(int i=0;i<arrData.count;i++)
{
NSString * str = [arrData objectAtIndex:i];
if ([str isEqualToString:#"en_US"] && i<arrData.count-1)
{
NSString* countryName = [arrData objectAtIndex:i+1];
NSLog(#"countryName %#", countryName);
}
}
But you should manage data in your file, loading from resource.
Best way to do it is
NSString *string = [NSString stringWithFormat: #"%#, %#, %#", var1, var2, var3];
Excuse the formatting/syntax errors. Typing this via iPhone. But if there is any errors, look up stringWithFormat: in iOS documents on the apple developer page for corrections.
Your string seems to have the following pattern:
A number,
An other number,
The country language code,
The name,
A short code,
An (other) name.
So what you can do is to use a loop like this:
for (int i = 0; i < dfd.count; i += 6) {
if ( dfd[i + 2] ) } // check the country code at index i + 2
// Do something
}
}

how to insert a Dictionary into an array

I am quite new to iOS and Objective-c.
I am trying to auto generate a pList in my app that looks like this.
I've so far been able to create the file making it a normal Value => Key file if i replace my for loop by
for (NSString* exercisePictureName in bigPictureData) {
[data setObject:exercisePictureName forKey:exercisePictureName];
}
but my problem is that I have no idea how to structure the logic at the end of my loop to create a file structure like shown in the picture. As it has to be exact.
Could anyone point me in the right direction on how to structure my loop so that it creates the file with the right format????
- (void) createImageListFromSource {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"exercisePictures.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: path])
{
path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: #"exercisePictures.plist"] ];
}
//To insert the data into the plist
NSArray* bicepPictureData = [self getAllimagesThatStartWith:#"bicep-"];
NSArray* tricepPictureData = [self getAllimagesThatStartWith:#"tricep-"];
NSArray* absPictureData = [self getAllimagesThatStartWith:#"abs-"];
NSArray* chestPictureData = [self getAllimagesThatStartWith:#"chest-"];
NSArray* backPictureData = [self getAllimagesThatStartWith:#"back-"];
NSArray* bigPictureData = [bicepPictureData arrayByAddingObjectsFromArray:tricepPictureData];
bigPictureData = [bigPictureData arrayByAddingObjectsFromArray:absPictureData];
bigPictureData = [bigPictureData arrayByAddingObjectsFromArray:chestPictureData];
bigPictureData = [bigPictureData arrayByAddingObjectsFromArray:backPictureData];
NSArray* finalData = [[NSArray alloc] init];
for (NSString* exercisePictureName in bigPictureData) {
NSDictionary* data = [[NSDictionary alloc] initWithObjectsAndKeys:exercisePictureName,#"text",exercisePictureName,#"image", nil];
[finalData arrayByAddingObject:data];
NSLog(#"%#",data);
}
NSLog(#"%#",finalData);
[finalData writeToFile: path atomically:YES];
}
What you have is an array of dictionaries. Pseudocode to show the structure:
NSMutableArray* arr = [NSMutableArray array];
for (...) {
NSDictionary* d = #{#"image": something, #"text": somethingelse};
[arr addObject:d];
}
When you are all done, just save the array directly with writeToURL....

iOS - App crash without error during loop process

during a loop process, my App crash without error. The array count is equal to 175260. With profiler I don't have leaks, so I don't know why the App exit, maybe the CPU usage 100% during a lot of time?
Thank you for your help.
Just this code following crash the App :
for(unsigned int i = 0; i <14;i++)
{
if(findSensor[i]==YES)
{
for(unsigned int j = 1; j <[array count];j++)
{
#autoreleasepool {
if([[[[array objectAtIndex:j] componentsSeparatedByString:#";"] objectAtIndex:0] isEqualToString:[NSString stringWithFormat:#"%d",10*(i+1)]])
{
//Code here
}
}
}
}
}
The full code is :
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fileName = [NSString stringWithFormat:#"%#/%#",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase];
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:fileName];
NSFileHandle *output = [NSFileHandle fileHandleForReadingAtPath:[NSString stringWithFormat:#"%#/%#10",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase]];
if(output == nil)
{
NSManagedObjectContext *context = [self managedObjectContext];
_recordlocal = [NSEntityDescription insertNewObjectForEntityForName:#"RECORD" inManagedObjectContext:context];
_recordlocal.date = [ibNavSettings interfaceSettings].selectedFileToDataBase;
NSData *inputData = [NSData dataWithData:[fh readDataToEndOfFile]];
NSString *inputString = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];
NSArray *array = [[NSArray alloc] initWithArray:[inputString componentsSeparatedByString:#"\n"]];
for(unsigned int i = 0; i <14;i++)
{
if(findSensor[i]==YES)
{
[[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)] contents:nil attributes:nil];
NSMutableString *saveString = [[NSMutableString alloc] init];
int count = 0;
for(unsigned int j = 1; j <[array count];j++)
{
#autoreleasepool {
if([[[[array objectAtIndex:j] componentsSeparatedByString:#";"] objectAtIndex:0] isEqualToString:[NSString stringWithFormat:#"%d",10*(i+1)]])
{
[saveString appendString:[array objectAtIndex:j]];
[saveString appendString:#"\n"];
if(i == 0)
count++;
progress++;
pourcent = progress/total;
load = pourcent*100;
if(load%5==0)
[self performSelectorInBackground:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
}
}
}
[saveString writeToFile:[NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)] atomically:YES encoding:NSUTF8StringEncoding error:nil];
if(i == 0)
_recordlocal.count = [[NSNumber alloc] initWithInt:(count/50)];
}
}
_recordlocal.load = [[NSNumber alloc] initWithBool:YES];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Core data error %#, %#", error, [error userInfo]);
abort();
}
I would guess that your app is crashing without a readable exception because it is running out of available RAM, especially since you indicated that it is running through a large number of iterations.
For a test, I would recommend doing what Rikkles suggests with the autorelease pool. In addition, since the value of i (and as a result the comparison string) rarely changes, I would create that string outside the j loop as well. This would avoid the creation of a lot of extra strings laying around.
Beyond that, since it appears that you are looking for a string at the beginning of a string that is delimited by a semicolon, I would recommend instead of doing componentsSeparatedByString and then examining element zero that you use the NSString method hasPrefix to check for the condition you are looking for.
Here is an example:
for(unsigned int i = 0; i <14;i++)
{
NSString *searchString = [NSString stringWithFormat:#"%d;", 10*(i+1)];
if(findSensor[i]==YES)
{
for(unsigned int j = 1; j <[array count];j++)
{
if([[array objectAtIndex:j] hasPrefix:searchString])
{
//Code here
}
}
}
}
(I hope this compiles and runs, if it doesn't it should require more than minor tweaks. I am away from my Mac right now.)
If this doesn't help, then something going on inside //Code here must be the culprit.
Why are you creating [array count] autoreleasepools? What's the point of creating so many of them? It could crash because of that. Put the #autoreleasepool outside the for loop.
The only reason I could think that you would do that is if you create so many transient objects inside each iteration of the for loop that you'd want to get rid of them as soon as you got out of the iteration. But there are other ways to do that, including reusing those objects within each iteration.
First suggestion
Just use fast enumeration for the inner loop, you aren't actually using the index 'j' for anything
https://developer.apple.com/library/mac/documentation/General/Conceptual/DevPedia-CocoaCore/Enumeration.html
Second suggestion
Put some NSLog's in place, it will slow everything down, but you need to figure out what point you are failing at. That will help point everyone in the right direction.
Third suggestion
Actually use NSError objects and output their value if an error is thrown:
NSError *writeError = nil;
[saveString writeToFile:[NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)]
atomically:YES
encoding:NSUTF8StringEncoding
error:&writeError];
if(error != nil) NSLog(#"error writing file: %#", [[writeError userInfo]description]);
Fourth suggestion
You appear to try to be updating the UI from a background thread. This will not work or will cause a crash. UI code can only be called from a main thread. So dont do this:
[self performSelectorInBackground:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
If you are already on a background thread this will probably crash because you are creating threads on threads on threads. You instead would want to call:
[self performSelectorOnMainThread:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
Fifth suggestion
You may be going over the maximum length for NSString (it's big but I did it once on accident before). You should probably just be appending the file on each iteration of the loop instead, so you don't have an ever growing NSMutableString:
NSString *path = [NSString stringWithFormat:#"%#/%#%d",documentsDirectory,[ibNavSettings interfaceSettings].selectedFileToDataBase,10*(i+1)]
NSFileHandle *fh = [NSFileHandle fileHandleForWritingAtPath:filePath];
NSData *newLine = [#"\n" dataUsingEncoding:NSUTF8StringEncoding];
for(NSString *rowString in array)
{
if([[[rowString componentsSeparatedByString:#";"] objectAtIndex:0] isEqualToString:[NSString stringWithFormat:#"%d",10*(i+1)]])
{
NSData *stringData = [rowString dataUsingEncoding:NSUTF8StringEncoding];
[fh truncateFileAtOffset:[fh seekToEndOfFile]];
[fh writeData:stringData];
[fh truncateFileAtOffset:[fh seekToEndOfFile]];
[fh writeData:newLine];
if(i == 0)
count++;
progress++;
pourcent = progress/total;
load = pourcent*100;
if(load%5==0)
[self performSelectorOnMainThread:#selector(changeUI:)withObject:[NSNumber numberWithFloat:(pourcent)]];
}
}
}
And this has the added benefit of helping you ditch the autoreleasepools
This was invalid
If your array does in fact have 175260 rows, that is probably your issue. You are looping using unsigned int as your index var. Unsigned ints in c only have a max value of 65535. Use an unsigned long int, max 4294967295.

iOS release not working as expected

I am using this code to get book names from a config.plist file. However my memory management is problematic. The '[dict release]' breaks the app completely and it exits.
The code works when the '[dict release]' is removed but it causes memory leaks as far as I can tell.
bnames is a global NSMutableArray
What am I doing wrong?
- (NSString *)loadBookname: (NSInteger) bookToLoad {
bookToLoad = [self bookOrder:bookToLoad];
//---get the path to the property list file---
plistFileNameConf = [[self documentsPath] stringByAppendingPathComponent:#"Config.plist"];
//---if the property list file can be found---
if ([[NSFileManager defaultManager] fileExistsAtPath:plistFileNameConf]) {
//---load the content of the property list file into a NSDictionary object---
dict = [[NSDictionary alloc] initWithContentsOfFile:plistFileNameConf];
bnames = [dict valueForKey:#"BookNames"];
[dict release];
}
else {
//---load the property list from the Resources folder---
NSString *pListPath = [[NSBundle mainBundle] pathForResource:#"Config" ofType:#"plist"];
dict = [[NSDictionary alloc] initWithContentsOfFile:pListPath];
bnames = [dict valueForKey:#"BookNames"];
[dict release];
}
plistFileNameConf = nil;
NSString *bookNameTemp;
bookNameTemp = [bnames objectAtIndex:bookToLoad - 1];
NSLog(#"bookName: %#", bookNameTemp);
return bookNameTemp;
}
You need to allocate your array properly:
bnames = [[NSArray alloc] initWithArray:[dict valueForKey:#"BookNames"]];
Double check that your dict returns the right data type.
There does not appear to be anything wrong with the way you allocate NSDictionary (although you could also use the [NSDictionary dictionaryWithContentsOfFile:] and save yourself having to worry about the release.
Either way I would suggest the issue is not with the [release] but probably the line BEFORE release:
bnames = [dict valueForKey:#"BookNames"];
a) Where is that allocated. I don't see an allocation or declaration of it anywhere?
b) What type of value do you expect back?
Put a break point on it and make sure your getting what you expect or anything.
If dict is not already a strong property, make it one. Then, use self.dict when assigning to it (and keep the release).
I've found what appears to be a better solution to the issue. This lets iOS manage the memory.
//---finds the path to the application's Documents directory---
- (NSString *) documentsPath {
NSLog(#"Start documentsPath");
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
// NSLog(#"Found documentsPath 40");
NSLog(#"End documentsPath");
return documentsDir;
}
- (NSString *) configPath {
NSLog(#"Start configPath");
NSString *plistFileNameConf = [[self documentsPath] stringByAppendingPathComponent:#"Config.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistFileNameConf]) {
plistFileNameConf = [[NSBundle mainBundle] pathForResource:#"Config" ofType:#"plist"];
}
NSLog(#"plistFile: %#",plistFileNameConf);
NSLog(#"End configPath");
return plistFileNameConf;
}
The following calls the above code as necessary:
NSString *Choice;
NSArray *properties;
NSString *errorDesc = nil;
NSPropertyListFormat format;
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:[self configPath]];
NSDictionary *temp = (NSDictionary *)[NSPropertyListSerialization propertyListFromData:plistXML mutabilityOption:NSPropertyListMutableContainersAndLeaves format:&format errorDescription:&errorDesc];
if (!temp) {
NSLog(#"Error reading plist: %#, format: %d", errorDesc, format);
}
Choice = [temp objectForKey:#"Choice"];
properties = [temp objectForKey:Choice];

Storing and reading files from Documents directory iOS 5

In my game, when a level is completed the app stores a "1" in a file in the Documents directory of the app. When the game then loads, a player can only play a level if the previous level has been completed. When I test the game via Xcode and on a device the app works properly and a level cannot be played until the previous level has been completed. However, when the app was approved and released on the App Store, the app behaves as if each level has been completed (no locked levels). I can't figure this one out and would appreciate someone's help! The devices I'm testing on are all iOs 5.0 or higher.
Below is the code that saves the completed level in the Documents directory:
NSMutableData* data = [[NSMutableData alloc] init];
NSKeyedArchiver* coder = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
NSString *levelString = [NSString stringWithFormat:#"Level%d",level];
[coder encodeInteger:1 forKey:levelString];
[coder finishEncoding];
NSString *levelString2 = [NSString stringWithFormat:#"Level%d.save",level];
///
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Identify the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
dataFile = [docsDir stringByAppendingPathComponent:levelString2];
// Check if the file already exists
if ([filemgr fileExistsAtPath: dataFile])
{
[[NSFileManager defaultManager] removeItemAtPath:dataFile error:nil];
}
[data writeToFile:dataFile atomically:YES];
[coder release];
[data release];
}
#catch (NSException* ex)
{
CCLOG(#"level save failed: %#", ex);
}
Below is the code that reads the Document directory to see if the level has been completed:
if ([self loadCompletedLevels:6] == 1) { //// level gets unlocked **** }
-(int) loadCompletedLevels:(int)theLevel; {
int isLevelCompleted; //1 = completed
NSString* kSaveFile = [NSString stringWithFormat:#"Level%d.save",theLevel];
NSString *levelString = [NSString stringWithFormat:#"Level%d",theLevel];
#try
{
NSFileManager *filemgr;
NSString *dataFile;
NSString *docsDir;
NSArray *dirPaths;
filemgr = [NSFileManager defaultManager];
// Identify the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
// Build the path to the data file
dataFile = [docsDir stringByAppendingPathComponent:kSaveFile];
if ([[NSFileManager defaultManager] fileExistsAtPath:dataFile])
{
NSData* data = [[NSData alloc] initWithContentsOfFile:dataFile];
if (data && [data length] > 0)
{
NSKeyedUnarchiver* decoder = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
isLevelCompleted = [decoder decodeIntForKey:levelString];
[decoder release];
}
[data release];
}
if (isLevelCompleted == 1) {
levelCompleted = YES;
}
}
#catch (NSException* ex)
{
levelCompleted = NO;
}
return isLevelCompleted; }
You should probably use a different approach for storing your data, but the real problem is that you are not initializing the return value, isLevelCompleted. It is on the stack, and does not have a default value. It starts out with whatever happens to be at that stack location.
So, if you don't set it, it will have an arbitrary value.
Also, you should probably use BOOL for a boolean value, but if you make this:
int isLevelCompleted = 0; //1 = completed
you will initialize it to "false" so it must be explicitly changed to "true" by your code.

Resources