Reputation: 11961
I have this code here, basically it takes an array goes through each item and adds it to a string with a comma at the end and after the loop, remove the last comma:
NSString *areaDescriptionWSpaceCharacters = nil;
for(NSString *item in areaDescription)
{
[areaDescriptionWSpaceCharacters stringByAppendingString:[NSString stringWithFormat: @"%@,", item]];
}
areaDescriptionWSpaceCharacters = [areaDescriptionWSpaceCharacters substringToIndex:[areaDescriptionWSpaceCharacters length] - 1];
but areaDescriptionWSpaceCharacters returns nil
. Why?
Upvotes: 0
Views: 482
Reputation: 2636
Your first line itself is the culprit here. You have not initialized the NSString yet so it will always be nil.
NSString *areaDescriptionWSpaceCharacters;
or
NSString *areaDescriptionWSpaceCharacters = @"";
or
NSString *areaDescriptionWSpaceCharacters = [[NSString alloc] init];
Upvotes: 1
Reputation: 130200
You are appending a string to nil
. You need to initialize the string to an empty string first.
NSString *areaDescriptionWSpaceCharacters = @"";
In this case you might consider using NSMutableString
.
NSMutableString *areaDescriptionWSpaceCharacters = [NSMutableString string];
for (NSString *item in areaDescription) {
if (areaDescriptionWSpaceCharacters.length > 0) {
[areaDescriptionWSpaceCharacters appendString:@","];
}
[areaDescriptionWSpaceCharacters appendString:item];
}
or directly
NSString *areaDescriptionWSpaceCharacters = [areaDescription componentsJoinedByString:@","];
(this task is so common there is a special method for it!)
Upvotes: 5