In a NSMutableDictionary like this:
[NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithString:firstName], #"NAME",
[NSNumber numberWithFloat:familyName], #"SURNAME",
nil];
How can all of its elements be converted to the NSString? with the requirement that names and surnames are arranged in string like this: "name, surname, name, surname..."?
This gives a string with all the names but not surnames:
NSString * result = [[urlArray valueForKey:#"NAME"] componentsJoinedByString:#", "];
Is there a way similar to the one above to create a string with all the values of NSMutableDictionary?
Try something like this:
NSString *result = [NSString stringWithFormat:#"%#, %#", [urlArray valueForKey:#"SURNAME"], [urlArray valueForKey:#"NAME"]];
The %# represents an objective-c object for more details see the Apple docs
The code to make a NSString from an NSDictionary may look like (if you're trying to print out everything in the NSDictionary)
NSMutableString* mutableString = [NSMutableString string];
NSDictionary* dictionary;
for(NSString* key in [dictionary allKeys])
{
[mutableString appendString:[[dictionary objectForKey:key] description]];
}
Related
I have a NSDictionary object with 2 items, the first one is a NSString and the second is an Integer. When I loop into the dictionary items I'd like detect what of they is an Integer.
What is the best way to do it?
The current dictionary is:
[[NSDictionary alloc] initWithObjectsAndKeys:#"San", #"name", #"123", #"id", nil]
The item you are putting in the dictionary is in no way an integer, it's a NSString which only contains numbers. Why not just use a NSNumber object and use it the way it should be?
[[NSDictionary alloc] initWithObjectsAndKeys:#"San", #"name", #123, #"id", nil]
This uses a literal for a NSNumber.
You can use isKindOfClass: to check if an object is of a specific class and enumerateKeysAndObjectsUsingBlock: to analyze every object contained in a dictionary.
For example:
NSDictionary *dictionary = #{#"name": #"San", #"id": #123};
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
if ([obj isKindOfClass:[NSNumber class]])
NSLog(#"%#: %# is a number", key, obj);
else
NSLog(#"%#: %# is NOT a number", key, obj);
}];
The first line is a NSDictionary creation using literals, the same is for #123, which automatically insert a NSNumber with 123 value in the dictionary.
Is there an easy way to take a user inputted NSString from an NSTextfield, and convert it to a valid objc regex?
I would like to escape all the '\' characters, but obviously not all the unneeded ones, i.e.... '\n', ' \xA9', '\r' etc....
for example this:
NSString *rejectString = #"^Steve\-Smi+.*+(\n)?"
needs to become this:
#"^Steve\\-Smi+.*+(\n)?"
I have ended up using NSPredicate instead, its much more user friendly:
NSArray *array = [NSArray arrayWithObjects: ojb1, obj2, obj3, obj4, nil];
NSMutableArray *filteredArray = [NSMutableArray new];
NSString *ignoreString = [ignoreStringTextfield stringValue];
for (NSString *name in array)
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT (SELF MATCHES %#)", ignoreString];
if ([predicate evaluateWithObject:name])
[filteredArray addObject:name];
}
return filteredArray;
I've got a NSDictionary and I'd like put all of it's objects and keys into a NSString, so that I can finally display them in a label like this:
key1: object1
key2: object2
key3: object3
... ...
Any ideas?
Build the string and then set it to the labels text.
NSMutableString *myString = [[NSMutableString alloc] init];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[myString appendFormat:#"%# : %#\n", key, obj];
}];
self.label.text = myString;
Note
The docs (String Programming Guide) for the %# format specifier state:
%#
Objective-C object, printed as the string returned by descriptionWithLocale: if available, or description otherwise. Also works with CFTypeRef objects, returning the result of the CFCopyDescription function.
So if these are your own custom objects in the dictionary you will most likely need to override the description method to provide more meaningful output
Update
You mention that you need your output sorted by keys - dictionaries are not ordered so you will have to do it differently - this example assumes that your keys are strings
NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
NSMutableString *myString = [[NSMutableString alloc] init];
for (NSString *key in sortedKeys) {
[myString appendFormat:#"%# : %#\n", key, [dictionary objectForKey:key]];
}
self.label.text = myString;
try this
for(id key in [dictionary allKeys])
{
id value = [dictionary objectForKey:key];
NSLog(#"%# : %#", key, value);
}
NSString *row;
for (id key in dictionary) {
row = [NSString stringWithFormat:"%#: %#", key, [dictionary objectForKey:key]];
// do something with your row string
}
Iam trying to append two time values from my TCTime object and display in label, even though I added "\n" towards the end it is printing only the first value but not the second value.
_feedTimes is NSArray.
NSMutableString *myString = [[NSMutableString alloc] init];
TCTime *time = _feedTimes[indexPath.row];
[myString appendFormat:#"%s : %#\n", "Time 1 ", time.Time1];
[myString appendFormat:#"%s : %#\n", "Time 2 ", time.Time2];
self.label.text = myString;
I have created a NSDictionary like following :
NSArray * alphabets = [NSArray arrayWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"o",#"p",#"q",#"r",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z",nil];
alphaToNum = [NSMutableDictionary dictionary];
numToAlpha = [NSMutableDictionary dictionary];
for(NSString* character in alphabets)
{
[alphaToNum setObject:[NSNumber numberWithInteger:index] forKey:character];
[numToAlpha setObject:character forKey:[NSNumber numberWithInteger:index]];
index++;
}
now I want to access to "numToAlpha" like following :
NSInteger code1;
NSNumber * nn = [numToAlpha objectForKey:code1];
and I'll get error whereas in manual for objectforkey it clearly said (id)objectforkey(id) which means anything!
NSInteger is not an object. id refers to any object type. You need to use [NSNumber numberWithInteger:code1] as you are already doing in your code sample.
I save pieces of data from my Cocoa application into a text file. The text file contains information as shown:
foo1 -> foo2
blah -> lwjef
hi -> bye
hello -> goodbye
Now the first part of each row is given by the user, but I need to get the part of each row after the ->. For example, if the user enters foo1, I want to output foo2 after parsing the text file. Does anyone know how to do this?
Parse once:
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSArray *lines = [string componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
for (NSString *line in lines) {
NSArray *values = [line componentsSeparatedByString:#" -> "];
if ([values count] != 2) {
continue;
}
[dictionary setObject:[values objectAtIndex:1] forKey:[values objectAtIndex:0]];
}
Then query for keys:
NSString *input = #"foo1";
NSString *answer = [dictionary objectForKey:input]; //#"foo2"
However, if the data originally came from your own application in the first place you should probably do this, instead of a custom (and insecure) string format:
//For saving:
[dictionary writeToFile:filePath atomically:YES];
//For loading:
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:filePath];