Passing Array From Controller to View
I have:
- UIView
- UIViewController
In the UIViewController I need to be able to insert items into a fixed array of 6 i开发者_运维知识库ntegers. Then, I need to pass this array to the view in order for it to analyse the array and update the screen appropriately. How do I go about doing this? I've tried using standard C arrays but doesn't seem to work?
You can't use C arrays as arguments to methods, nor can you pass them to something. You have two options:
- Use an NSArray of six NSNumbers, each containing an int.
- Use a pointer to the C array.
Which one you choose is up to you. Option 1 is more iPhone-alike. Option 2 is less memory-consuming.
Because objective c doesn't allow C arrays to be passed to objective c methods unless they are sent as pointers, Here is one method:
// MyViewController.m
#define BOX_INT(ARG_1) [NSNumber numberWithInt:ARG_1];
....
-(void) somethingHappened:(id) sender
{
// initialize the array:
NSArray *array = [NSArray arrayWithObjects:BOX_INT(ints[0]), BOX_INT(ints[1]), BOX_INT(ints[2]), BOX_INT(ints[3]), BOX_INT(ints[4]), BOX_INT(ints[5]), nil];
[myView passArray:array];
}
// MyView.m
#define UNBOX_INT(ARG_1) [ARG_1 intValue];
....
-(void) passArray:(NSArray *) array
{
int intArray[6];
for (int i = 0; i < 6; i++)
{
intArray[i] = UNBOX_INT([array objectAtIndex:i]);
}
...
}
Or, you can just pass a pointer (not recommended)
// MyController.m
-(void) somethingHappened:(id) sender
{
[myView passArray:ints];
}
-(void) passArray:(int *) array
{
// think of array as an integer array, with a length of 6.
}
There' has always been a discussion for how to share objects between two classes . So broadly speaking there are three methods:-
- Singleton Objects
- Global Variables
- Appdelegate variables
However if u really want to pass an array from ViewController to View , I would recommend going with 3rd method i.e. AppDelegate Variables. And yes that's always pointed that this is quick but Dirty method.
So what you can do is declare and Array in Appdelegate.
Now to insert items into that array in ur viewcontroller
UrAppDelegate* delegate = (UrAppDelegate*)[[UIApplication sharedApplication]delegate];
[delegate.urArrayName addObject:@"someObject"];
And then when u want to use that in ur view.. just go ahead and use the same method above.
精彩评论