如何解析NSArray只参与每个数组条目?

时间:2014-07-08 15:26:37

标签: ios objective-c arrays cocoa

这是我的数组,这是我后端的回复

NSArray  *myArray = [NSArray arrayWithObjects:@"  userId: 123, online: 0, subscriptionState: none",@"  userId: 124, online: 0, subscriptionState: none",@"  userId: 125, online: 1, subscriptionState: none",nil];
NSLog(@"this is an example array=%@", myArray);]

日志:

this is an example array=(
    "  userId: 123, online: 0, subscriptionState: none",
    "  userId: 124, online: 0, subscriptionState: none",
    "  userId: 125, online: 1, subscriptionState: none"
)

我想从这个数组中只提取用户ID号来创建一个像这样的日志输出的新数组

this is the new array=(
        "123",
        "124",
        "125"
    )

1 个答案:

答案 0 :(得分:2)

尝试创建一个新的Class User:NSObject并使用一组用户,而不是尝试解析这些东西。如果您正在跟踪每个用户的项目,那么您确实需要一个用户类来包含它。这将允许您使用User对象而不是您解析的字符串。这为您提供了更多的功能,灵活性和更清晰的代码。

User.h

@interface User : NSObject

@property (nonatomic) int userId;
@property (nonatomic) BOOL isOnline;
@property (nonatomic) int subscriptionState;

然后在你的课堂上:

User *user1 = [User new];
user1.userId = 123;
user1.isOnline = NO;
user1.subscriptionState = 0;
...

NSArray *usersArray = [NSArray arrayWithObjects:user1,user2,user3,nil];
for (User *curUser in usersArray)
{
   NSLog(@"User ID: %d", curUser.userId);
}

现在,您可以打印出他们是否在线,他们的订阅状态是什么,并且还可以非常轻松地对用户进行更新。之前,如果用户更改了他们的订阅状态或者他们联机,则必须手动更新用户的整个NSString。例如,如果User1联机,则必须将其重置为:@" userId: 123, online: 1, subscriptionState: none"。这是非常混乱和很多工作。现在你可以这样做:

 user1 = [usersArray objectAtIndex:0];
 user1.isOnline = YES;

更新:

我注意到这是从后端返回的。请注意,如果无法修复后端,这是如何使其与后端返回一起使用。除非你被迫使用,否则使用这种方法是非常未提及的。

NSArray *wordArray = [userString componentsSeparatedByString:@","];
NSString *userId = [[[wordArray objectAtIndex:0] componentsSeparatedByString:@":"] objectAtIndex:1];
NSString *online = [[[wordArray objectAtIndex:1] componentsSeparatedByString:@":"] objectAtIndex:1];
NSString *subscriptionStatus = [[[wordArray objectAtIndex:2] componentsSeparatedByString:@":"] objectAtIndex:1];