当前位置: 动力学知识库 > 问答 > 编程问答 >

objective c - Construct NSString from the description method of each NSArray item?

问题描述:

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: