Vahid Hashemi
Vahid Hashemi

Reputation: 5240

I'm not able to get NSArray as return value from a function

I'm try to get a point based structure from a function called:

-(NSArray *) calcRose : (float) theta
{
    //first calculate x and y 
    //we need to get width and height of uiscreen

    //myPoint[0] = [UIScreen mainScreen].applicationFrame.size.width;

    NSMutableArray *Points = [[NSMutableArray alloc ] arrayWithCapacity:2];

    float angle = [self radians:theta];
    float side = cos(n * angle);
    int cWidth = 320;
    int cHeight = 240;
    float width = cWidth * side * sin(angle) / 2 + cWidth /2;
    float height = cHeight * side * cos(angle) / 2 + cHeight /2;

    [Points addObject:[NSNumber numberWithFloat:cWidth]];
    [Points addObject:[NSNumber numberWithFloat:cHeight]];
    NSArray *myarr = [[[NSArray alloc] initWithArray:Points ]autorelease ];

    return myarr;
}

I use below code for retrieving data from the function:

NSArray *tt = [[ NSArray alloc] initWithArray:[self calcRose:3]     ];

But every time I compile the program it gives me some error.

How can I solve this problem?

Upvotes: 0

Views: 147

Answers (2)

jrturton
jrturton

Reputation: 119242

I guess you've simplified your sample for the purposes of the question but you seem to be doing a lot of unnecessary work. The code in your question could be rewritten as:

-(NSArray *) calcRose : (float) theta 
{   
    int cWidth = 320;     
    int cHeight = 240;     

    return [NSArray arrayWithObjects:[NSNumber numberWithFloat:cWidth],[NSNumber numberWithFloat:cHeight],nil];        
} 

initWithCapacity and using a mutable array is not really giving you anything besides a headache. If you want to use a mutable array, just create with [NSMutableArray array], but it doesn't look like you are adding that many objects so the method I have suggested would be better.

This method returns an autoreleased array, so your calling statement can just be

NSArray *tt = [self calcRose:3];

Upvotes: 1

MrMage
MrMage

Reputation: 7487

[[NSMutableArray alloc ] arrayWithCapacity:2] definitely is wrong. Try [NSMutableArray arrayWithCapacity:2] instead. Also, you can just use [[self calcRose:3] retain] rather than [[NSArray alloc] initWithArray:[self calcRose:3]], and you only need the retain call if you intend to keep the array around for longer than the current runloop pass.

Upvotes: 3

Related Questions