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'
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]);
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".
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.
This should work:
@interface MyClass { int _doubleDigits[10]; } @property(readonly) int *doubleDigits; @end @implementation MyClass - (int *)doubleDigits { return _doubleDigits; } @end
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With