简体   繁体   中英

Copy NSMutablearray to another

I am trying to copy NSMutableArray to another but it does not show me anything at the UITableView :

NSMutableArray *objectsToAdd= [[NSMutableArray alloc] initWithObjects:@"one",@"two"];

NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:objectsToAdd,nil];

NSMutableArray *list = [[NSMutableArray alloc] init];

[self.list addObjectsFromArray:myArray];

Nothing show up! What is wrong?

It crashes my app because I do not have nil at my NSMutableArray how can I add nil to it? addobject:nil does not work it crashes the app:

static NSString * DisclosureButtonCellIdentifier = 
@"DisclosureButtonCellIdentifier";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: 
                         DisclosureButtonCellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                   reuseIdentifier: DisclosureButtonCellIdentifier]
            autorelease];
}
NSUInteger row = [indexPath row];

NSString *rowString =nil;

rowString = [list objectAtIndex:row];


cell.textLabel.text = rowString;

cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
[rowString release];
return cell;

Your initial call to alloc an NSMutableArray will most likely crash, since you don't have a nil terminator in your argument list.

Also, you have a local variable, list, and a property, list. Make sure you're instantiating what you think you are. You might need to do this:

NSMutableArray *objectsToAdd= [[NSMutableArray alloc] initWithObjects:@"one",@"two", nil];

NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:objectsToAdd,nil];

self.list = [[NSMutableArray alloc] init];

[self.list addObjectsFromArray:myArray];

This might help you:

NSMutableArray *result  = [NSMutableArray arrayWithArray:array];

or

NSMutableArray *result = [array mutableCopy]; //recommended

There are a few problems... One problem is that you're using 'initWithObjects' and adding the previous array. This seems like unwanted behaviour since you most likely want to add the strings @"one" and @"two" to the array. You most likely intended to use initWithArray or addObjectsFromArray . (Doing it the way you did, will add the NSMutableArray (not its objects) to the list)

The second problem, when you use initWithObjects, you need to list each of the objects and then terminate the list with a nil value. ( docs ) In other words, you need to use...

NSMutableArray *objectsToAdd = [[NSMutableArray alloc] initWithObjects:@"One", @"Two", nil];

问题可能是第4行的本地list声明与属性冲突。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM