Iphone Object C - Data, Objects and Arrays

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:

arrGrid[0].isEmpty = True;

      

I can't seem to find a link to create shared objects in object C. Can anyone help?

0


a source to share


2 answers


Well, assuming you are doing something with an iphone or mac in cocoa, you can just subclass NSObject (base class in objective-c).

You need .h and .m, so for you it would be something like this: (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

      

This defines a simple Slot object with 4 properties that can be accessed using dot notation, for example:



s = [[Slot alloc] init];
s.empty = YES;
s.xPos = 1.0;
s.yPos = 1.0;

      

There are many variations for which data types are used and how you define their properties, etc. depending on what data you are dealing with.

If you want to add slot object to 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];

      

+9


a source


If you only use this object instance to store named values, you can use an NSMutableDictionary instance instead, although you will 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 added them to NSMutableArray, allocated with [NSMutableArray array]

or similar:



[array addObject: obj];

      

To get integer / boolean values ​​from a dictionary, you must do the following:

int i = [[obj objectForKey: @"id"] intValue];
BOOL isEmpty = [[obj objectForKey: @"isEmpty"] boolValue];

      

+1


a source







All Articles