Data storage NSArray and NSMutableArray - Objective C
Data storage and its retrieval is one the most important in any program. In objective C, we generally won't depend on structures like linked list since it makes the work complex. Instead, we use the collection like NSArray , NSSet , NSDictionary and its mutable forms.
NSArray & NSMutableArray
NSArray is used to hold an immutable array of objects and the NSMutaableArray is used to hold an mutable array of object.
Mutability helps to change the array in runtime a preallocated array, but if we use NSArray , we only replace the existing array and cannot change the content of the existing array.
Important methods of NSArray are as follows:
Important methods of NSMutableArray are as follows:
In the above program , we have seen a simple differntiation between NSMutableArray and NSArray where we can insert a string after allocation in mutable array.
NSArray & NSMutableArray
NSArray is used to hold an immutable array of objects and the NSMutaableArray is used to hold an mutable array of object.
Mutability helps to change the array in runtime a preallocated array, but if we use NSArray , we only replace the existing array and cannot change the content of the existing array.
Important methods of NSArray are as follows:
- alloc/initWithObjcts: used to initalized array with objects.
- objectAtIndex: return the object at the specific index.
- count: return the number of objects.
Important methods of NSMutableArray are as follows:
- removeAllObjects : Empties the array
- addObject : inserts a given object at the end of the array
- removeObjectAtIndex : This is used to remove objectAt a specific index
- exchangeObjectAtIndex : withObjectAtIndex : Exchange the objects in the array at given indices.
- replaceObjectAtIndex : withObject : Replace the object at index with an object.
#import <Foundation/Foundation.h>
int main()
{
NSArray *arrobj = [[NSArray alloc]initWithObjects : @"raj", @"ram",@"rahul",nil];
NSString *strobj = [[arrobj objectAtIndex: 0];
NSLog(@"The object in array at index 0 is %@", strobj);
NSMutableArray *mutarrobj = [[NSMutableArray alloc]init];
[mutarrobj addObject : @"sunena"];
strobj = [ mutarrobj objectAtIndex : 0];
NSLog(@"The object in array at index 0 is %@", strobj);
return 0;
}
int main()
{
NSArray *arrobj = [[NSArray alloc]initWithObjects : @"raj", @"ram",@"rahul",nil];
NSString *strobj = [[arrobj objectAtIndex: 0];
NSLog(@"The object in array at index 0 is %@", strobj);
NSMutableArray *mutarrobj = [[NSMutableArray alloc]init];
[mutarrobj addObject : @"sunena"];
strobj = [ mutarrobj objectAtIndex : 0];
NSLog(@"The object in array at index 0 is %@", strobj);
return 0;
}
In the above program , we have seen a simple differntiation between NSMutableArray and NSArray where we can insert a string after allocation in mutable array.
NSMutableArray
No comments: