Sort the list items in A to Z order - iphone

I have list of items and want to sort them in A to Z order like Contact list does. Could anyone please help me to understand how to do this? Any documentation on this would be appreaciated.
Thanks.

In order to display/arrange your data in alphabetical order which in a array you have to use NSSortDescriptorthere is a core data tutorial in the devlopers document of X-Code and here it is coreDataBooks and its a best one try to take help from there see how they are displaying the data in alphabetical order also refer here.

NSSortDescriptor *sortByName= [[NSSortDescriptor alloc] initWithKey:#"self" ascending:NO selector:#selector(compareName:)];
if(sortByName)
{
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:sortByName]];
[sortByUnlockLevel release];
}
And in your modal implement the method compareName
- (NSComparisonResult)compareName:(id)inObject
{
NSComparisonResult result = NSOrderedSame;
result = [Object.mName compare:self.mName];
return result;
}

Related

Sort array with ÅÄÖ

I'm totally new to iPhone/OSX development and I'm trying to sort an NSMutableArray filled with objects in alphabetical order but I fail. Items starting with Å or Ä ends up with items starting with A and items starting with Ö ends up with items starting with O. I have tried different sorting methods that I have found here on Stackoverflow but none of them seems to work (for me at least)
NSSortDescriptor* stationDescriptor = [[NSSortDescriptor alloc]initWithKey:#"name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
NSArray* descriptors = [NSArray arrayWithObject:stationDescriptor];
[stations sortUsingDescriptors:descriptors];
[stations sortUsingComparator:^NSComparisonResult(Station* obj1, Station* obj2){
return [[obj1 name] localizedCaseInsensitiveCompare:[obj2 name]];
}];
Ok, progress! I have been successful in getting this to work by changing the language on the emulator to Swedish, is there any way I can get the same result when the phone is set to English? I know in C# you can send in a reference to a specific culture when sorting/comparing strings.
/Viktor
Looking at the docs for NSString gives you the answer.
You are using localizedCaseInsensitiveCompare: and the docs for this state
blah blah blah
See Also
– compare:options:range:locale:
So jumping to the docs for compare:options:range:locale: you can figure it out. You'll need something like
return [[obj1 name] compare:[obj2 name]
options:NSCaseInsensitiveSearch
range:NSMakeRange(0, [obj1 length])
locale:whateverLocaleYouWant];

NSMutableArray Not showing actual values when NSLog in iphone application

I am doing an NSLog of an array but instead of data it shows the following values. I do not know how to fix this issue and get the values from the array
if(!surveyQuestions){
surveyQuestions=[[NSMutableArray alloc]init];
}
Total Survey Questions 3
2012-07-31 08:54:53.555 SQL[442:9203] SurveyQuestions (
"<QuestionData: 0x4da10f0>",
"<QuestionData: 0x4b9f120>",
"<QuestionData: 0x4ba42e0>"
)
I'm not sure what you're trying to do but: it's certain that the poor array object has no idea what and how your own custom class does, its best possibility to print an instance of your class is to call its description method, which you see, and which is not really helpful. You maybe want to do two things:
I. If you only want to print your objects like this, override the description method of your class and use some format string (given that you haven't written a single line of code I have to fall back to guess):
- (NSString *)description
{
return [NSString stringWithFormat:#"Name: %#, address: %#", self.name, self.address];
}
II. If you want to use the data of your class elsewhere, you probably want to loop through its properties manually:
for (QuestionData *d in surveyQuestions)
{
NSLog(#"%#", d.name);
// etc.
}
You need to do something like this:
NSArray *theArray = [[NSArray alloc] initWith...];
NSLog(#"array contents: %#", theArray);

SBJson parsing help iphone

im currently trying to parse some json data on the iphone.
I have been trawling the web for examples, but none seem to suit my purpose, i am using SBJson.
What I want is to be able to get an NSArray of Titles, Artisits, Status, etc. so that I can display them on a table view. Any help would be great, so far all i get is an array of "Values".
JSON = {"values":
[
{"Status":"N", "Filename":"RD207T04", "Title":"Simple Man (Explicit)", "Artist":"DIAFRIX F/DANIEL MERRIWE", "Release":"May11"},
{"Status":"N", "Filename":"CR221T27", "Title":"Midnight City", "Artist":"M83", "Release":"Dec11"},
{"Status":"N", "Filename":"ED211T03", "Title":"I\"ll Be Your Man", "Artist":"JAMES BLUNT", "Release":"Jul11"}
]}
You don't want an array of titles, artists, etc. You want the array of NSDictionarys represented by the values key. Then you can do:
cell.textLabel.text = [[valuesArray objectAtIndex:indexPath.row]valueForKey:#"Title"]];
inside your cellForRowAtIndexPath: delegate method. If you do not have this already, this is how to get that array:
NSArray *valuesArray = [[myJsonString JSONValue]objectForKey:#"values"];
Thanks mate, I was definately over complicating things:
The end code was this:
NSArray *valuesArray = [[playlist JSONValue] objectForKey:#"values"];
NSString *test = [[valuesArray objectAtIndex:0]valueForKey:#"Title"];
NSLog(#"test = %#", test);
Now all I have to do is iterate through the set :)

Parsing XML Inner XML tags Objective-C

I would like to create an NSDictionary or (NSArray) full of NSDictionary objects for each station in the following XML:
<stations lastUpdate="1328986911319" version="2.0">
<station>
<id>1</id>
<name>River Street , Clerkenwell</name>
<terminalName>001023</terminalName>
<lat>51.52916347</lat>
<long>-0.109970527</long>
<installed>true</installed>
<locked>false</locked>
<installDate>1278947280000</installDate>
<removalDate/>
<temporary>false</temporary>
<nbBikes>12</nbBikes>
<nbEmptyDocks>7</nbEmptyDocks>
<nbDocks>19</nbDocks>
</station>
... more...
<station>
<id>260</id>
<name>Broadwick Street, Soho</name>
<terminalName>003489</terminalName>
<lat>51.5136846</lat>
<long>-0.135580879</long>
<installed>true</installed>
<locked>false</locked>
<installDate>1279711020000</installDate>
<removalDate/>
<temporary>false</temporary>
<nbBikes>12</nbBikes>
<nbEmptyDocks>4</nbEmptyDocks>
<nbDocks>18</nbDocks>
</station>
...
</stations>
What's the best way to achieve this? Right now I have an NSDictionary with one object and one key - "stations", but I want the NSDictionary (or NSArray) of NSDictionarys.
I'm using an XML parser by Troy Brant - http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
I'm guessing it's going to involve some looping of some sort but I'm not really sure how to approach this problem. Any help or pointers in the right direction would be much appreciated.
Thanks.
I also use the XMLReader it is very easy to understand
I have looked at your xml, and I am assuming you wanted to use the array of station tags.
Here is my solution:
NSDictionary *dictXML= [XMLReader dictionaryForXMLString:testXMLString error:&parseError];
NSArray *arrStation = [[dictXML objectForKey:#"stations"] objectForKey:#"station"];//this would return the array of station dictionaries
Now that you have the array of station tags you can do what you want for example displaying all id:
for(int i=0;i<[arrStation count];i++){
NSDictionary *aStation = [arrStation objectAtIndex:i];
NSLog(#"id = %#",[aStation objectForKey:#"id"]);
}
also you can write less code using the fast enumeration loop:
for(NSDictionary *aStation in arrStation){
NSLog(#"id = %#",[aStation objectForKey:#"id"]);
}
hope that helps :)
The best way would be to create subclasses of NSObject that map to each tag. That would be way more cleaner than using Dictionaries and Arrays.

Searching for an id in Core Data

I am getting some unexpected behavior with CoreData and NSPredicate. In a large database population I have different Managed Objects relating to one-another. However, I have a problem with the following. When giving an id (NSNumber, given as NSString to this function) I don't get a result unless I save the whole context first. I don;t want to do that as it takes too much time (as it is a large set of data). The code is:
- (DOSite *) findSite:(NSString *) siteId {
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"(id = %#)", siteId];
[NSFetchedResultsController deleteCacheWithName:nil];
[[self fetchedResultsController].fetchRequest setPredicate:predicate];
NSError *fetchError;
if (![[self fetchedResultsController] performFetch:&fetchError]) {
// Handle the error.
// This is a serious error and should advise the user to restart the application
NSLog(#"Fetching data error: %#", [fetchError localizedDescription]);
}
if([[[self fetchedResultsController] fetchedObjects] count] == 0){
return NULL;
}
return (DOSite *)[[[self fetchedResultsController] fetchedObjects] objectAtIndex:0];
}
So when I add an x number of items (using +[NSEntityDescription insertNewObjectForEntityForName:inManagedObjectContext:]) doing a search on all items return the right amount of items.
When searching for a string (e.g.predicateWithFormat:#"(name LIKE %#)") I get positive results, but when using the above code predicateWithFormat:#"(id = %#) I get zero results.
The only way I can get results is to save the whole context and then perform the fetchRequest, then suddenly it works.
So there must be something small I do wrong in searching for the id, I just seem to be blind to find it and spend two days at it now to narrow it down to this point. Is there anybody who can give me some advice on this?
This may not work, but have you tried using a name more complex than "id" in your entity (like "SiteID")? Sometimes very short names overlap with other system properties and it causes odd issues.
The problem was that I gave a NSString to the predicate as outlined above. When changing that to an int (ie predicateWithFormat:#"(id == %i)") it works fine for some reason.