开发者

split NSString into Core Data

I am just learning Core Data.

I am trying to split a NSString into Core Data.

So far I have a string like this:

NSString *testStr = @"Sam,Milton Keynes,01234567890";

And am splitting that into an Array like this:

NSArray *array = [[NSArray alloc] init];
    array = [testStr componentsSeparatedByString:@","];

Then putting that into Core Data:

newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];

    [newContact setValue:[array objectAtIndex:0] forKey:@"name"];
    [newContact setValue:[array objectAtIndex:1] forKey:@"address"];
    [newContact setValue:[array objectAtIndex:2] forKey:@"phone"];

This works fine for the testStr I am using, but I want to be able to have a string with multiple records, and split that into Core Data - example of string want to use:

NSString *testStr = @"Sam,Milton Keynes,01234567890|Hannah,Milton Keynes,021654768431|Adam,Broughton,4244开发者_如何转开发5454542";

I can do what ive done above, then split that array further, but my question is: How do i do this and store into Core data?

any help much appreciated

Sam


Well you need first split the sting on | and the loop thru the array. Then just insert you original code:

NSString *testStr = @"Sam,Milton Keynes,01234567890|Hannah,Milton Keynes,021654768431|Adam,Broughton,42445454542";

NSArray *personArray = [testStr componentsSeparatedByString:@"|"];

for(NSString *person in personArray) {
   NSArray *array = [person componentsSeparatedByString:@","];
   newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];

    [newContact setValue:[array objectAtIndex:0] forKey:@"name"];
    [newContact setValue:[array objectAtIndex:1] forKey:@"address"];
    [newContact setValue:[array objectAtIndex:2] forKey:@"phone"];
}

PS, don't alloc an array if you if you are going to fill it later with an other instance of NSArray:

NSArray *array = [[NSArray alloc] init];
    array = [testStr componentsSeparatedByString:@","];

Here you just leaked a NSArray.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜