Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of integers property in Objective-C

I'm having troubles creating a property of an array of integers in Objective-C. I'm not sure whether this is even possible to do in Obj-C so I'm hoping someone can help me in finding out either how to do it correctly or provide an alternative solution.

myclass.h

@interface myClass : NSObject {  @private int doubleDigits[10]; }  @property int doubleDigits; @end 

myclass.m

@implementation myClass      @synthesize doubleDigits;     -(id) init {          self = [super init];          int doubleDigits[10] = {1,2,3,4,5,6,7,8,9,10};          return self;     }      @end 

When I build and run, I get the following error:

error: type of property 'doubleDigits' does not match type of ivar 'doubleDigits'

like image 464
jebcrum Avatar asked Jan 24 '09 23:01

jebcrum


People also ask

How to create int array in Objective-C?

You can use a plain old C array: NSInteger myIntegers[40]; for (NSInteger i = 0; i < 40; i++) myIntegers[i] = i; // to get one of them NSLog (@"The 4th integer is: %d", myIntegers[3]);

How to create array in Objective-C?

Creating an Array Object For example: NSArray *myColors; myColors = [NSArray arrayWithObjects: @"Red", @"Green", @"Blue", @"Yellow", nil]; The above code creates a new array object called myColors and initializes it with four constant string objects containing the strings "Red", "Green", "Blue" and "Yellow".

How do I create an NSDictionary in Objective-C?

Creating NSDictionary Objects Using Dictionary Literals In addition to the provided initializers, such as init(objects:forKeys:) , you can create an NSDictionary object using a dictionary literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:forKeys:count:) method.


2 Answers

This should work:

@interface MyClass {     int _doubleDigits[10];  }  @property(readonly) int *doubleDigits;  @end  @implementation MyClass  - (int *)doubleDigits {     return _doubleDigits; }  @end 
like image 140
robottobor Avatar answered Nov 07 '22 18:11

robottobor


C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:

Supported Types

You can declare a property for any Objective-C class, Core Foundation data type, or “plain old data” (POD) type (see C++ Language Note: POD Types). For constraints on using Core Foundation types, however, see “Core Foundation.”

POD does not include C arrays. See http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html

If you need an array, you should use NSArray or NSData.

The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.

like image 26
lucius Avatar answered Nov 07 '22 17:11

lucius