Reputation: 367
So I'm a Flash guy and I'm trying to convert the following code to Object C:
var slot:Object = new Object();
slot.id = i;
slot.xPos = 25*i;
slot.yPos = 25*i;
slot.isEmpty = False;
// push object to array
arrGrid.push(slot);
Later I can override like:
arrGrid[0].isEmpty = True;
I can't seem to find a reference to creating generic objects in Object C. Can someone help?
Upvotes: 0
Views: 5111
Reputation: 11156
If you're only using this Object instance to store named values, you can use an instance of NSMutableDictionary instead, although you'll need to wrap your integer values with NSNumber instances:
NSMutableDictionary * obj = [NSMutableDictionary dictionary];
[obj setObject: [NSNumber numberWithInt: i] forKey: @"id"];
[obj setObject: [NSNumber numberWithInt: i*25] forKey: @"xPos"];
[obj setObject: [NSNumber numberWithInt: i*25] forKey: @"yPos"];
[obj setObject: [NSNumber numberWithBool: NO] forKey: @"isEmpty"];
Then you'd add these to an NSMutableArray allocated using [NSMutableArray array]
or similar:
[array addObject: obj];
To get the integer/boolean values out of the dictionary, you'd do the following:
int i = [[obj objectForKey: @"id"] intValue];
BOOL isEmpty = [[obj objectForKey: @"isEmpty"] boolValue];
Upvotes: 1
Reputation: 9507
Well assuming you are doing something with the iphone or mac in cocoa you can simply subclass NSObject (the base class in objective-c).
You need a .h and .m so for you example it would be something like: (Note that I used slotId instead of id because id is a keyword in objective-c)
Slot.h
// Slot.h
@interface Slot : NSObject {
NSInteger slotId;
float xPos;
float yPos;
BOOL empty;
}
@property NSInteger slotId;
@property float xPos;
@property float yPos;
@property BOOL empty;
@end
// Slot.m
#import "Slot.h"
@implementation Slot
@synthesize slotId;
@synthesize xPos;
@synthesize yPos;
@synthesize empty;
@end
That defines a simple Slot object with 4 properties which can be accessed using dot notation such as:
s = [[Slot alloc] init];
s.empty = YES;
s.xPos = 1.0;
s.yPos = 1.0;
There are a lot of variations for which data types you use and how you define the properties, etc depending on what kind of data you are dealing with.
If you wanted to add a slot object to an array one simple example:
// create an array and add a slot object
NSMutableArray *arr = [NSMutableArray array];
Slot *slot = [[Slot alloc] init];
[arr addObject:slot];
// set the slot to empty
[[arr objectAtIndex:0] setEmpty:YES];
Upvotes: 9