NSMutableArray with NSDictionary to Labels without the surrounding brackets - objective-c

I'm making a scoreboard for my game. And when I do a NSLog of the data it comes out as this:
{
name = TTY;
score = "3.366347";
}
So my question is how do I remove this brackets and also just grab the name (TTY) and score (3.36 without the quotations) and place them in variable for me to put into labels.
Currently I can place them in labels but they have the lingering curly braces "{" and "}".
Any hints would be helpful as I'm happy to search further I just don't know the vocab to search for it.
thanks

For NSDictionary if you want to get the values you use objectForKey: method;
[scoreDictionary objectForKey:#"name"];
In your case the method will return TTY
You can store this in a variable like normal:
NSString *entryName = [scoreDictionary objectForKey:#"name"];
For NSArray (and NSMutableArray) you use objectAtIndex: method;
[scoresArray objectAtIndex:0];
I'm guessing that you have many NSDictionary in the NSArray, in which case you can combine the two methods above and get;
[[scoresArray objectAtIndex:0] objectForKey:#"name"];
which will give you the value of name in the first dictionary of the array.
Also if you want to access multiple key values you can use;
NSDictionary *entry = [scoresArray objectAtIndex:0];
NSString *entryName = [entry objectForKey:#"name"];
NSString *entryScore = [entry objectForKey:#"score"];

Related

removing null from arrays in Object-c

I have this snipped of code that results in an array with a whole bunch of "<null>" throughout and I need to figure out how to remove them. Obviously after smashing my head against the keyboard I'm asking for some help.
In my .h I have declared:
NSArray *sortedContacts;
NSArray *rawContacts;
And then in .m:
-(void) buildContacts {
ABAddressBook *addressBook = [ABAddressBook sharedAddressBook];
NSArray *contacts = [addressBook people];
rawContacts=contacts;
NSArray *firstNames = [rawContacts valueForKey:#"First"];
NSArray *lastNames = [rawContacts valueForKey:#"Last"];
NSArray *organization = [rawContacts valueForKey:#"Organization"];
NSMutableArray *fullNames = [NSMutableArray array];
for(int i = 0; i < [firstNames count]; i++)
{
NSString *fullName = [NSString stringWithFormat:#"%# %# %#",
[firstNames objectAtIndex:i],
[lastNames objectAtIndex:i],
[organization objectAtIndex:i]];
[fullNames addObject:fullName];
}
NSMutableArray *fullList = [[NSMutableArray alloc]initWithArray:fullNames];
[fullList removeObjectIdenticalTo: #"<null>"];
sortedContacts = [fullList sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"%#",sortedContacts);
}
I've tried so many things that I just can't see the forest for the trees anymore.
The text <null> is how the singleton instance of NSNull describes itself. That is, it's what -[NSNull description] returns.
In turn, these NSNull objects are getting into your firstNames, lastNames, and organization arrays because that's what Key-Value Coding does when you call -valueForKey: on an array and some of the elements return nil when that message is forwarded on to them with the same key. That is, calling [rawContacts valueForKey:#"First"] causes NSArray to call [element valueForKey:#"First"] for each element in rawContacts and to put the result in the array it builds. But, since an array can't contain nil, if one of those elements returns nil from [element valueForKey:#"First"], an NSNull object is added in its place.
Then, you are formatting the string fullName from the corresponding elements of firstNames, lastNames, and organization. You need to check if any of those elements are NSNull using if ([value isKindOfClass:[NSNull class]]) and handling that. For instance, you might just skip that record. Or you might combine the available fields and leave out any unavailable ones.
In any case, none of the elements of fullList will be #"<null>" because formatting values into #"%# %# %#" can never result in that string. (It might be #"<null> <null> <null>" or something like that, but never just #"<null>".)
A quick look at your code suggests you cannot get any empty strings added to your array, (a) you add elements using:
[fullNames addObject:fullName];
and fullName is created using:
[NSString stringWithFormat:#"%# %# %#" ...
so even if the %#'s get replaced by nothing you'll still have 2 spaces...
Maybe this is why all the things you've tried fail, if you're looking for empty strings you won't find them.
(Addendum: Question now says you're looking for #"<null>", you won't get that either for the same reason - there is at least two spaces in your string.)
The simple answer to removing invalid entries in fullNames is not to add them in the first place. You are adding elements in a loop (for), and conditional logic (e.g. if) inside the loop to determine whether you have something valid to add - however you define "something valid" - and only add an item to fullNames if so.
HTH
I'm not really familiar with the AddressBook framework, however this might be what's causing the confusion:
The values you collect in your arrays firstNames, lastNames and organization can be of type NSString or NSNull. You have to do any null-checking within the for-loop, before the fullName-string is constructed.
Remove this useless line:
[fullList removeObjectIdenticalTo: #"<null>"];
And replace the contents of your for-loop with the following code:
for(int i = 0; i < [firstNames count]; i++)
{
NSString *firstName = [firstNames objectAtIndex:i];
NSString *lastName = [lastNames objectAtIndex:i];
NSString *org = [organization objectAtIndex:i];
NSMutableArray *namesArray = [NSMutableArray array];
if ([firstName isKindOfClass:[NSString class]])
[namesArray addObject:firstName];
if ([lastName isKindOfClass:[NSString class]])
[namesArray addObject:lastName];
if ([org isKindOfClass:[NSString class]])
[namesArray addObject:org];
if (namesArray.count > 0)
[fullNames addObject:[namesArray componentsJoinedByString:#" "]];
}

Having trouble taking an index of an array and making it an NSString

I get an array from a JSON and I parse it into an NSMutableArray (this part is correct and working). I now want to take that array and print the first object to a Label. Here is my code:
NSDictionary *title = [[dictionary objectForKey:#"title"] objectAtIndex:2];
arrayLabel = [title objectForKey:#"label"];
NSLog(#"arrayLabel = %#", arrayLabel); // Returns correct
//Here is where I need help
string = [arrayLabel objectAtIndex:1]; //I do not get the first label (App crashes)
NSLog(#"string = %#", string);
other things that I have already tried are as follows:
string = [NSString stringWithFormat:#"%#", [arrayImage objectAtIndex:1]];
and
string = [[NSString alloc] initWithFormat:#"%#", [arrayImage objectAtIndex:1]];
Any help is greatly appriciated!
EDIT: The app does not return a single value and crashes.
Your code doesn't match the structure of your JSON. In your comment on the deleted answer, you said you got an exception when sending objectAtIndex: to an NSString. In your case, arrayLabel isn't an array when you think it is.
If your JSON has an object, your code needs to treat it as an NSDictionary. Likewise for arrays and NSArray and strings and NSString.
In addition to whatever else was going on, you repeatedly refer to "first" but use the index 1. In most C-based programming languages (and others, as well) the convention is that indexes into arrays are 0-based. So, use index 0 to get the first element.

Create Instance variables at runtime

I want to create instance variables dynamically at runtime, and I want to add these variables to a category. The number of the instance variables may change based on the configuration/properties file which I am using for defining them.
Any ideas??
Use Associative References - this is tricky, but that is the mechanism invented specifically for your use case.
Here is an example from the link above: first, you define a reference and add it to your object using objc_setAssociatedObject; then you can retrieve the value back by calling objc_getAssociatedObject.
static char overviewKey;
NSArray *array = [[NSArray alloc] initWithObjects:# "One", #"Two", #"Three", nil];
NSString *overview = [[NSString alloc] initWithFormat:#"%#", #"First three numbers"];
objc_setAssociatedObject (
array,
&overviewKey,
overview,
OBJC_ASSOCIATION_RETAIN
);
[overview release];
NSString *associatedObject = (NSString *) objc_getAssociatedObject (array, &overviewKey);
NSLog(#"associatedObject: %#", associatedObject);
objc_setAssociatedObject (
array,
&overviewKey,
nil,
OBJC_ASSOCIATION_ASSIGN
);
[array release];
I'd be inclined to just use a NSMutableDictionary (see NSMutableDictionary Class Reference). Thus, you would have an ivar:
NSMutableDictionary *dictionary;
You'd then initialize it:
dictionary = [NSMutableDictionary dictionary];
You can then save values to it dynamically in code, e.g.:
dictionary[#"name"] = #"Rob";
dictionary[#"age"] = #29;
// etc.
Or, if you are reading from a file and don't know what the names of the keys are going to be, you can do this programmatically, e.g.:
NSString *key = ... // your app will read the name of the field from the text file
id value = ... // your app will read the value of the field from the text file
dictionary[key] = value; // this saves that value for that key in the dictionary
And if you're using an older version of Xcode (before 4.5), the syntax is:
[dictionary setObject:value forKey:key];
Depends on exactly what you want to do, the question is vague but if you want to have several objects or several integers or so on, arrays are the way to go. Say you have a plist with a list of 100 numbers. You can do something sort of like this:
NSArray * array = [NSArray arrayWithContentsOfFile:filePath];
// filePath is the path to the plist file with all of the numbers stored in it as an array
That will give you an array of NSNumbers, you can then turn that into an array of just ints if you want like this;
int intArray [[array count]];
for (int i = 0; i < [array count]; i++) {
intArray[i] = [((NSNumber *)[array objectAtIndex:i]) intValue];
}
Whenever you want to get an integer from a certain position, lets say you want to look at the 5th integer, you would do this:
int myNewInt = intArray[4];
// intArray[0] is the first position so [4] would be the fifth
Just look into using a plist for pulling data, it will them be really easy to create arrays of custom objects or variables in your code by parsing the plist.

Sort ignoring punctuation (Objective-C)

I am trying to sort an iOS UITableView object. I am currently using the following code:
// Sort terms alphabetically, ignoring case
[self.termsList sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
This sorts my list, whist ignoring case. However, it would be nice to ignore punctuation as well. For example:
c.a.t.
car
cat
should be sorted as follows:
car
c.a.t.
cat
(It doesn't actually matter which of the two cats (cat or c.a.t.) comes first, so long as they're sorted next to one another).
Is there a simple method to get around this? I presume the solution would involve extracting JUST the alphanumeric characters from the strings, then comparing those, then returning them back to their former states with the non-alphanumeric characters included again.
In point of fact, the only characters I truly care about are periods (.) but if there is a solution that covers all punctuation easily then it'd be useful to know.
Note: I asked this exact same question of Java a month ago. Now, I am creating the same solution in Objective-C. I wonder if there are any tricks available for the iOS API that make this easy...
Edit: I have tried using the following code to strip punctuation and populate another array which I sort (suggested by #tiguero). However, I don't know how to do the last step: to actually sort the first array according to the order of the second. Here is my code:
NSMutableArray *arrayWithoutPunctuation = [[NSMutableArray alloc] init];
for (NSString *item in arrayWithPunctuation)
{
// Replace hyphens/periods with spaces
item = [item stringByReplacingOccurrencesOfString:#"-" withString:#" "]; // ...hyphens
item = [item stringByReplacingOccurrencesOfString:#"." withString:#" "]; // ...periods
[arrayWithoutPunctuation addObject:item];
}
[arrayWithoutPunctuation sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
This provides 'arrayWithoutPunctuation' which is sorted, but of course doesn't contain the punctuation. This is no good, since, although it is now sorted nicely, it no longer contains punctuation which is crucial to the array in the first place. What I need to do is sort 'arrayWithPunctuation' according to the order of 'arrayWithoutPunctuation'... Any help appreciated.
You can use a comparison block on an NSArray and your code will look like the following:
NSArray* yourStringList = [NSArray arrayWithObjects:#"c.a.t.", #"car", #"cat", nil];
NSArray* yourStringSorted = [yourStringList sortedArrayUsingComparator:^(id a, id b){
NSString* as = (NSString*)a;
NSString* bs = (NSString*)b;
NSCharacterSet *unwantedChars = [NSCharacterSet characterSetWithCharactersInString:#"\\.:',"];
//Remove unwanted chars
as = [[as componentsSeparatedByCharactersInSet: unwantedChars] componentsJoinedByString: #""];
bs = [[as componentsSeparatedByCharactersInSet: unwantedChars] componentsJoinedByString: #""];
// make the case insensitive comparison btw your two strings
return [as caseInsensitiveCompare: bs];
}];
This might not be the most efficient code actually one other option would be to iterate on your array first and remove all unwanted chars and use a selector with the caseInsensitiveCompare method:
NSString* yourStringSorted = [yourStringList sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
This is a bit cleaner, and a bit more efficient:
NSArray* strings = #[#".....c",#"a.",#"a",#"b",#"b...",#"a..,"];
NSArray* sorted_strings = [strings sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSString* a = [obj1 stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
NSString* b = [obj2 stringByTrimmingCharactersInSet:[NSCharacterSet punctuationCharacterSet]];
return [a caseInsensitiveCompare:b];
}];
For real efficiency, I'd write a compare method that ignores punctuation, so that no memory allocations would be needed just to compare.
My solution would be to group each string into a custom object with two properties
the original string
the string without punctuation
...and then sort the objects based on the string without punctuation.
Objective C has some handy ways to do that.
So let's say we have two strings in this object:
NSString *myString;
NSString *modified;
First, add your custom objects to an array
NSMutableArray *myStrings = [[NSMutableArray alloc] init];
[myStrings addObject: ...];
Then, sort the array by the modified variable using the handy NSSortDescriptor.
//You can specify the variable name to sort by
//Sorting is done according to the locale using localizedStandardCompare
NSSortDescriptor *mySortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"modified" ascending:YES selector:#selector(localizedStandardCompare:)];
[myStrings sortedArrayUsingDescriptors:#[ mySortDescriptor ]];
Voila! Your objects (and strings) are sorted. For more info on NSSortDescriptor...

How does one populate an NSMutable array of NSMutableSets?

I am using this code in a loop to populate an NSMutable Array of NSMutableSets (of NSString objects). The index of the NSSet is based on the length of the word.
// if set of this length not initialized yet, initialize set.
wordIndex = [NSString stringWithFormat:#"%d", currentWordLength];
if ([myWordArray objectForKey:wordIndex] == nil)
[myWordArray setObject:[[NSMutableSet alloc] initWithObjects:currentWord, nil] forKey:wordIndex];
else
[[myWordArray objectForKey:wordIndex] addObject:currentWord];
The final intention is to split up an array of words into an array of sets of words grouped by their lengths.
However, I see that [myWordArray count] is 0 after this. Why?
You are confusing the methods of NSMutableDictionary and NSMutableArray: In Objective-C arrays do not have keys but have indexes. If you change the class for myWordArray to NSMutableDicitionary it should work.
Try this, it looks very much like your logic, but (1) it uses NSNumbers as keys, which makes a little more sense, (2) handles the missing set condition more simply, but just adding the set, and (3) breaks up the source lines somewhat for easier debugging...
NSArray *inputStrings = // however these are initialized goes here
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSString *currentString in inputStrings) {
NSInteger currentWordLength = currentString.length;
wordIndex = [NSNumber numberWithInt:currentWordLength];
NSMutableSet *wordSet = [result objectForKey:wordIndex];
if (!wordSet) {
wordSet = [NSMutableSet set];
[result setObject:wordSet forKey:wordIndex];
}
[wordSet addObject:currentWord];
}
If you still have an empty dictionary after running this, it might be simpler to watch what's happening by stepping through it.