Reputation: 701
I know that you guys may feel that this is repetitive question. But I'm screwed up with this issue with my project.
Now moving to the issue, I have taken an NSMutableArray
named arr1
that contains string values such as @"34"
, @"40"
and so on. Now, I have second NSMutableArray
named arr2
. I have already tried below code.
[arr1 initWithObjects:@"1",@"2", nil];
arr2 = [[[NSMutableArray alloc] initWithArray:arr1 copyItems:YES] autorelease];
Then, I tried
NSString *no = [arr2 objectAtIndex:0];
tst.text = no;
However, it gives me no value in my textbox.
If any1 can help me out with this would be great help.
Upvotes: 1
Views: 8142
Reputation: 38728
Your arr1
must be nil
otherwise you would crash, but more to the point you are creating the NSMutableArray
incorrectly:
You should not really do alloc
and init
on separate lines
NSMutableArray *myArray = [NSMutableArray alloc];
NSLog(@"%@", [myArray class]);
//=> __NSPlaceholderArray
In this case the myArray
pointer is pointing at a flyweight of type __NSPlaceholderArray
which is most likely not what you want. You would prefer:
---------------------------------------
myArray = [[NSMutableArray alloc] init];
NSLog(@"%@", [myArray class]);
//=> __NSArrayM
You will also crash if you do have a legitimate NSMutableArray
and you call initWithArray:
with:
[NSMutableArray initWithCapacity:]: method only defined for abstract class.
This is because the method is most likely defined on __NSPlaceholderArray
Upvotes: 2
Reputation: 151
In addition to tia's answer: you need to allocate it first.
The method 'mutableCopy' will create a copy of the array, not of the elements inside it. You could create a new immutable array with 'initWithArray:arr1 copyItems:YES' and subsequently create a mutable version of it by calling 'mutableCopy'.:
NSArray *arr1 = [[NSArray alloc] initWithObjects:@"1",@"2", nil];
NSMutableArray arr2 = [[[NSArray alloc] initWithArray: arr1 copyItems:YES] mutableCopy];
Upvotes: 0
Reputation: 112873
[arr1 initWithObjects:@"1",@"2", nil];
makes no sense, what you probably want is to use the NSMutableArray
:
NSArray *arr1 = [NSArray arrayWithObjects:@"1",@"2", nil];
NSMutableArray *arr2 = [arr1 mutableCopy];
NSLog(@"arr1: %p, %@", arr1, arr1);
NSLog(@"arr2: %p, %@", arr2, arr2);
NSLog output:
arr1: 0x7924c50, (
1,
2
)
arr2: 0x7924f00, (
1,
2
)
Upvotes: 6
Reputation: 3870
Are you trying [arr2 objectAtIndex:0]
in the same method where arr2
is being created?
Maybe the problem is that you are using autorelease
on your arr2
. So, in other methods it may have lost its values.
I tried the following and it works for me:
NSMutableArray * arr1 = [[NSMutableArray alloc]initWithObjects:@"1", @"2", nil];
NSMutableArray * arr2 = [[[NSMutableArray alloc] initWithArray:arr1 copyItems:YES] autorelease];
NSString * no = [arr2 objectAtIndex:0];
NSLog(@"%@", no);
Upvotes: 0
Reputation: 9718
Your arr1 might be nil. It should be
arr1 = [[NSArray alloc] initWithObjects:@"1", @"2", nil];
Upvotes: 3