Reputation: 29
Here is my array which is the response from my backend
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);]
Log:
this is an example array=(
" userId: 123, online: 0, subscriptionState: none",
" userId: 124, online: 0, subscriptionState: none",
" userId: 125, online: 1, subscriptionState: none"
)
I want to extract only the userID numbers from this array to make a new array that would have a log output like this
this is the new array=(
"123",
"124",
"125"
)
Upvotes: 1
Views: 93
Reputation: 1414
Try creating a new Class User:NSObject
and using an array of Users instead of trying to parse this stuff out. If you're tracking items for each user, then you really need a user class to contain it. This will allow you to use User objects instead of a string that you parse out. This gives you a lot more power, flexibility, and cleaner code.
User.h
@interface User : NSObject
@property (nonatomic) int userId;
@property (nonatomic) BOOL isOnline;
@property (nonatomic) int subscriptionState;
Then in your class:
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);
}
Now you can print out if they're online, what their subscriptionState is, and also make updates to a user very easy. Before, you would have to manually update the whole NSString
for the user if they changed their subscriptionState or if they came online. For example, if User1 came online, then you would have to reset it to: @" userId: 123, online: 1, subscriptionState: none"
. This is extremely messy and a lot of work. Now you can just do:
user1 = [usersArray objectAtIndex:0];
user1.isOnline = YES;
UPDATE:
It was brought to my attention this is return from a backend. Note this is how to make it work with the backend return if you cannot fix the backend. It is highly unsuggested to use this type of method unless you're forced to.
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];
Upvotes: 2