I got a dictionary with 10 arrays and each array got 20 elements. How can i access the 18th element of an each array? pointers please. Thanks. Attaching my log file
for (NSString *key in [dictionary allKeys])
{
NSArray *menuList = [dictionary objectForKey:key];
NSString *imageName = [menuList objectAtIndex:17];
NSLog(#"Image Name:%#", imageName);
}
It seems what you actually wanted was
NSString *imageName = [dictionary objectForKey:#"episodeImagePath"];
Use the following code
//iterate all values
for (NSArray *arr in yourDictionary.allValues) {
//To loop the array
for (NSString *str in arr) {
NSLog(#"Element %#", str);
}
}
i think its better to take one object class, so that we can get all 18th elements in one array
Related
I have a word list stored in an NSArray, I want to find all the words in it with the ending 'ing'.
Could someone please provide me with some sample/pseudo code.
Use NSPredicate to filter NSArrays.
NSArray *array = #[#"test", #"testing", #"check", #"checking"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF ENDSWITH 'ing'"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];
Let's say you have an array defined:
NSArray *wordList = // you have the contents defined properly
Then you can enumerate the array using a block
// This array will hold the results.
NSMutableArray *resultArray = [NSMutableArray new];
// Enumerate the wordlist with a block
[wordlist enumerateObjectsUsingBlock:(id obj, NSUInteger idx, BOOL *stop) {
if ([obj hasSuffix:#"ing"]) {
// Add the word to the result list
[result addObject:obj];
}
}];
// resultArray now has the words ending in "ing"
(I am using ARC in this code block)
I am giving an example using blocks because its gives you more options should you need them, and it's a more modern approach to enumerating collections. You could also do this with a concurrent enumeration and get some performance benefits as well.
Just loop through it and check the suffixes like that:
for (NSString *myString in myArray) {
if ([myString hasSuffix:#"ing"]){
// do something with myString which ends with "ing"
}
}
NSMutableArray *results = [[NSMutableArray alloc] init];
// assuming your array of words is called array:
for (int i = 0; i < [array count]; i++)
{
NSString *word = [array objectAtIndex: i];
if ([word hasSuffix: #"ing"])
[results addObject: word];
}
// do some processing
[results release]; // if you're not using ARC yet.
Typed from scratch, should work :)
I have an NSArray, where each object contains a specific class called Card. Card has a description method. I want to join all objects in the array using the output of the description method, separated by spaces. Is there a simple to do this, without manually iterating the NSArray and manipulating NSString?
Something akin to the following made-up code?
NSArray *myArray = getCards(); // fetches 10 items or more
NSString *myString = [myArray joinUsingDescriptionMethodSeparatedBy:#" "];
or
NSString *myString = [NSString stringFromArrayDescriptionMethods:myArray separatedBy:#" "];
Naturally ,I could implement this myself but I suspect there could be something already present that does this.
I don't think that there is such a method. You can also implement it in a Category for NSString.
Sorry, I found this:
NSString * result = [[array valueForKey:#"description"] componentsJoinedByString:#""];
From the documentation:
Constructs and returns an NSString object that is the result of
interposing a given separator between the elements of the array.
- (NSString *)componentsJoinedByString:(NSString *)separator
Do this for description method of each NSArray item:
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in array)
{
[result appendString:[NSString stringWithFormat:#" %#"[obj description]]];
}
NSLog(#"The concatenated string is %#", result);
I am trying to split the string into parts and insert into a table how should i do it?
I got an error for splitting of the array which is: -[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance 0x7a421e0
NSArray *BusRoute = alightDesc;
int i;
int count = [BusRoute count];
for (i = 0; i < count; i++)
{
NSDictionary *dic = [BusRoute objectAtIndex: i];
NSDictionary *STEPS = [dic valueForKey:#"STEPS"];
NSString *AlightDesc = [STEPS valueForKey:#"AlightDesc"];
NSLog(#"AlightDesc = %#", AlightDesc);
NSArray *aDescArray = [AlightDesc componentsSeparatedByString:#","];
NSLog(#"aDescArray = %#", aDescArray);
}
This is the string which I'm splitting, i got it from the NSLog
AlightDesc = (
"Block1",
"Block2",
"Block3"
)
please help I'm stuck thanks.
Objective C is not a strongly typed language. All you know for sure about [STEPS valueForKey:#"AlightDesc"] is that it will return an object (of type id). When you wrote NSString *AlightDesc = [STEPS valueForKey:#"AlightDesc"] the compiler did not complain because NSString * is a valid object type. Unfortunately there is a logic error in your code so that what was actually stored under the key #"AlightDesc" is an NSArray. As others have mentioned, NSArray does not respond to componentsSeparatedByString: so you get an error at runtime.
The easy fix for this is to correct your logic: Either store an NSString in the first place or treat what you get out as an NSArray. As #janusfidel mentioned you can use an NSArray perfectly well in a table by using objectAtIndex: to get the string for the entry you want.
In some more complicated cases you may not know what you will be getting out of a dictionary for a particular key. In that case in Objective C you can just ask the object:
id anObject = [STEPS valueForKey:#"AlightDesc"];
if ([anObject isKindOfClass:[NSString class]]) {
NSString *aString = (NSString *)anObject;
// Treat as a string ...
} else if ([anObject isKindOfClass:[NSString class]]) {
// Object is an array ...
Your NSString *AlightDesc should look like this
NSString *AlightDesc = "Block1,Block2,Block3";
NSArray *aDescArray = [AlightDesc componentsSeparatedByString:#","];
If your string is what you say it is
AlightDesc = ("Block1","Block2","Block3");
then your string is the problem because it's already broken up.
I have an NSMutableArray where each item is an NSMutableDictionary.
NSMutableAray *services = [NSMutableArray new];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject: aNetService forKey: #"net_service"];
[dict setObject: [aNetService name] forKey: #"net_service_name"];
[self.services addObject:dict];
Then I want to retrieve an item according to the "net_service_name" key. So, I tried the following:
-(void)netServiceBrowser:(NSNetServiceBrowser *)aBrowser didRemoveService:(NSNetService *)aNetService moreComing:(BOOL)more {
NSLog(#"netservname%#",[aNetService name]);
for (int i = 0; i < [services count]; i++)
{
NSDictionary *dict = [services objectAtIndex:i];
NSLog(#"netservname%#",[dict objectForKey:#"net_service_name"]);
if ([NSString stringWithFormat:#"%#",[dict objectForKey:#"net_service_name"]] == [NSString stringWithFormat:#"%#",[aNetService name]]){
NSLog(#"Match");
}
}
}
In the console both NSLog(#"netservname") are the same, but I'm not getting the "Match" message. Can anyone see why? Thanks very much!
Try using
if ([[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]).
== checks for identity, that is whether the two objects point to the same memory address.
isEqualToString checks for equality, in this case, that the two strings are the same characters in the same order.
[[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]
Try that.
try this:
[[NSString stringWithFormat:#"%#",[dict objectForKey:#"net_service_name"]] isEqualToString:[NSString stringWithFormat:#"%#",[aNetService name]]]
or
[[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]
NSString isEqualToString:(NSString*) http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html
see: Case-insensitive NSString comparison
Because Objective-C uses pointers for everything you can't directly compare strings with the == operator. What you're looking for is:
[string isEqualToString: otherString]
Always use isEqualToString: for NSString comparison.
(And in general, always use isEqual: and its variants for NSObject comparisons)
NSObject* and NSString* are pointers, so == do pointer comparison which is only true if the pointers are pointing to the exact same address in memory, which is quite never the case, while isEqualToString: check if the contents of the string are identical.
Besides, you should prefer fast enumerations form for your for loop, and avoid doing stuff like stringWithFormat:#"%#" which are totally useless (you are creating a string using a format that will only contain... another string. Why don't you use the string itself directly?)
// NSFastEnumeration for to loop thru a NSArray
for (NSDictionary *dict in services)
{
NSLog(#"netservname%#",[dict objectForKey:#"net_service_name"]);
// Loose the [NSString stringWithFormat:#"%#",...] stuff!!
if ([[dict objectForKey:#"net_service_name"] isEqualToString:[aNetService name]]) {
NSLog(#"Match");
}
}
Try to replace if-statement with this one:
if ([[dict objectForKey:#"net_service_name"] compare:[aNetService name]] == NSOrderedSame) {
NSLog(#"Match");
}
I need to display the list of names which I am getting from the parser. I am getting the NSMutable arrary of list, then i need to display them in alphabetical order.
I tried doing what is given as:
NSArray *myArtistArray=[[NSArray alloc]init];
myArtistArray=[artistsList sortUsingSelector:#selector(compare:) ];
// error void value not ignored as it outght to be
[myArtistArray sortedArrayUsingSelector:#selector(compare:)];
[yourMutableArray sortUsingSelector:#selector(compare:)];
[yourArray sortedArrayUsingSelector:#selector(compare:)];
[yourMutableArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSArray *arraysort=[[NSArray alloc] initWithObjects:#"z",#"v",#"a",#"g",#"b", nil];
NSArray *sortedArray = [arraysort sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
for (NSString *str in sortedArray) {
NSLog(#"string %# ",str);
}
NSLog(#"sortedarrayelements %d",[sortedArray count]);
[yourArrayName sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];