Monday, 15 June 2015

ios - Initialize Array of Objects using NSArray -



ios - Initialize Array of Objects using NSArray -

i'm pretty new objective-c , ios i've been playing around picker view. i've defined person class when create new person automatically gives person name , age.

#import "person.h" @implementation person @synthesize personname, age; -(id)init { self = [super init]; if(self) { personname = [self randomname]; age = [self randomage]; } homecoming self; } -(nsstring *) randomname { nsstring* name; nsarray* namearr = [nsarray arraywithobjects: @"jill valentine", @"peter griffin", @"meg griffin", @"jack lolwut", @"mike roflcoptor", @"cindy woods", @"jessica windmill", @"alexander great", @"sarah peterson", @"scott scottland", @"geoff fanta", @"amanda pope", @"michael meyers", @"richard biggus", @"montey python", @"mike wut", @"fake person", @"chair", nil]; nsuinteger randomindex = arc4random() % [namearr count]; name = [namearr objectatindex: randomindex]; homecoming name; } -(nsinteger *) randomage { //lowerbound + arc4random() % (upperbound - lowerbound); nsinteger* num = (nsinteger*)(1 + arc4random() % (99 - 1)); homecoming num; } @end

now want create array of persons can throw bunch picker, pick 1 person , show age. first though need create array of persons. how create array of objects, initialize , allocate them?

nsmutablearray *persons = [nsmutablearray array]; (int = 0; < mypersonscount; i++) { [persons addobject:[[person alloc] init]]; } nsarray *arrayofpersons = [nsarray arraywitharray:persons]; // if want immutable array

also can reach without using nsmutablearray:

nsarray *persons = [nsarray array]; (int = 0; < mypersonscount; i++) { persons = [persons arraybyaddingobject:[[person alloc] init]]; }

one more thing - it's valid arc enabled environment, if going utilize without arc don't forget add together autoreleased objects array!

[persons addobject:[[[person alloc] init] autorelease];

ios objective-c arrays nsarray

No comments:

Post a Comment