iOS Objective-C: NSMutable Array returns garbage - objective-c

I'm trying to take a C-style vector and convert it into an NSMutable array object.
Here's the function:
+(NSMutableArray*)arrayFromPoints:(vector<Point2f>&)points
{
NSMutableArray* pointArray = [[NSMutableArray alloc] init];
for (int i=0;i<points.size();i++)
{
Point2f point = points[i];
JBPoint* point2 = [[JBPoint alloc]initWithX:point.x andY:point.y];
[pointArray addObject:point2];
}
return pointArray;
}
Custom point class:
#implementation JBPoint
float _x;
float _y;
-(id) initWithX:(float)x andY:(float)y
{
if (self=[super init])
{
_x = x;
_y=y;
}
return self;
}
-(float)x{ return _x;}
-(float)y {return _y;}
#end
Test output:
for (JBPoint* pnt in array)
{
NSLog(#"%f, %f", pnt.x, pnt.y);
}
I except it to output the array, but every time it just gives me the last value! does anyone know why?
I thought that they were maybe pointing to the same object, but they have different memory addresses.

So I figured out the problem. float _x;
float _y; where being treated like class variables instead of instance variables. Changed the class to:
#interface JBPoint()
{
float _x;
float _y;
}
#end
#implementation JBPoint
-(id) initWithX:(float)x andY:(float)y
{
if (self=[super init])
{
_x = x;
_y=y;
}
return self;
}
-(float)x{ return _x;}
-(float)y {return _y;}
#end

if you wrote
#property (nonatomic, readonly) float x;
#property (nonatomic, readonly) float y;
in your header file you wouldn't need to declare the instance variables (and would have avoided the issue here) and you could delete the getter methods your wrote as that would all be generated by the compiler for you and your custom init method would continue to work (with the most recent compiler).
Its a good idea to do this because:
less code
your intent is clear - 2 variables that are readonly for clients
follows language conventions
If you are using an older compiler (an older version of Xcode) then you would also have to #synthesize the accessors like this:
#synthesize x = _x;
Some interesting asides:
With the most recent complier you didn't need the class extension.
#implementation{
float _x;
float _y;
}
would also have worked.
As referenced in WWDC 2012 session video 413, the current recommended pattern to write an init method is:
...
self = [super init];
if (self) {
...
}
return self;

Related

Objective C getter method not working for property

I was playing around with objective C. This is my code for a class I wrote , arithmetic.h:
#import <Foundation/Foundation.h>
#interface arithmetic : NSObject
#property int cur;
-(id)initWithNumber:(int)number;
#end
#implementation arithmetic
#synthesize cur;
- (instancetype)init
{
self = [super init];
if (self) {
NSLog(#"Yo, all works :D ");
}
return self;
}
-(id)initWithNumber:(int)num{
self = [super init];
if(self){
[self setCur:8] ;
}
return self;
}
#end
Note the #property int cur. I was excepting objective c to create a setCur and a getCur method as accessors and mutators for my class. However, when I run this:
arithmetic *test = [[arithmetic alloc] initWithNumber:89];
[test setCur:534];
NSLog("%i",[test getCur ]);
The first two lines work. But the last line says
No visible interface for arithmetic declares the selector 'getCur'
What is the problem ?
It is because when you declare like this in your #implementation:
#synthesize cur;
it will create getter
-(int)cur {
return _cur;
}
and also it will create a setter
-(void)setCur:(int)newCur {
_cur = newCur;
}
In summary, Objective-C getter/setter is having a pattern of propery/setPropery respectively, unlike Java that uses getProperty/setProperty.
And Objective-C getter/setter is accessed via dot(.) notation. For example
int x = obj.cur;
obj.cur = 100;

Error: "Unrecognized selector" when using addObjects: on an NSMutableArray

When executing
[self.blockViews addObject:curBlockView];
I get an error
2011-07-01 13:35:26.240 Block Breaker[42061:207] -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x4e037a0
I am pretty new to Objective-C. Is it something in my init method?
//
// GameEngine.h
// Block Breaker
//
// Created by Chris Muench on 7/1/11.
// Copyright 2011 N/A. All rights reserved.
//
#import <Foundation/Foundation.h>
#interface GameEngine : NSObject {
NSMutableArray *blockViews;
int numBlockRows;
int score;
}
#property (nonatomic, copy) NSMutableArray *blockViews;
#property int numBlockRows;
#property int score;
- (void) setup;
- (void) setupBlocks;
#end
//
// GameEngine.m
// Block Breaker
//
// Created by Chris Muench on 7/1/11.
// Copyright 2011 N/A. All rights reserved.
//
#import "GameEngine.h"
#import "Block.h"
#import "BlockView.h"
#implementation GameEngine
#synthesize blockViews;
#synthesize numBlockRows;
#synthesize score;
- (id) init
{
if ((self = [super init]))
{
self.blockViews = [[NSMutableArray alloc] init];
self.numBlockRows = 2;
self.score = 0;
}
return self;
}
- (void) setup
{
[self setupBlocks];
}
- (void) setupBlocks
{
float blockWidth = 10;
float blockHeight = 10;
float rowSpacing = 2;
float colSpacing = 2;
float currentX = 0;
float currentY=10;
float screenWidth = 200;
for (int rowCounter=0;rowCounter<self.numBlockRows;rowCounter++)
{
while(currentX <=screenWidth)
{
Block *curBlock = [[Block alloc] initWithWidth:blockWidth height:blockHeight];
BlockView *curBlockView = [[BlockView alloc] initWithFrame:CGRectMake(currentX, currentY, curBlock.width, curBlock.height)];
curBlockView.block = curBlock;
[self.blockViews addObject:curBlockView];
currentX+=blockWidth+colSpacing;
[curBlock release];
[curBlockView release];
}
currentX=0;
currentY+=blockHeight+rowSpacing;
}
}
#end
When you copy an NSMutableArray using the copy method, or a synthesized setter for which the property was specified as copy, you get an immutable copy, which means you essentially end up with a plain NSArray.* There is a method mutableCopy which will preserve the mutability, but I don't believe there's any way to specify that for a property.
If you want your array to be mutably copied when you set it, you'll have to write your own setter method, and specify that method in the property declaration.
#property (nonatomic, copy, setter=setBlockViewsByCopying) NSMutableArray * blockViews;
- (void) setBlockViewsByCopying: (NSMutableArray *)newBlockViews {
NSMutableArray * tmp = [newBlockViews mutableCopy];
[blockViews release];
blockViews = tmp;
}
A side note, as #InsertWittyName mentioned in a comment, your code initializing blockViews will create a leak, because you have two claims of ownership on the array you're creating -- one for the alloc and one for the retain or copy that you get using the property:
self.blockViews = [[NSMutableArray alloc] init];
// ^ One claim ^ Two claims
// Only one release later, when the property is set again!
// LEAK!
You should instead do:
self.blockViews = [NSMutableArray array];
// Creates an object you don't own which you then make one claim
// on using the setter
*Though as it is a class cluster, you really get some unspecified concrete subclass.
Copy should retain, If I remember correctly.
Anyway using copying cannot be optimal, every time you call the accessor (set), you got a copy, and, as well pointed out above, is immutable.
Adding is fine, but remember to release the array when done.
Did you retain your array ??

iOS/Objective-C: NSInteger gets lost during simply Coordinates2D object creation

I'm tearing my hair out over this.. I've no idea what's going wrong.
I've created a very simple Coordinates2D class to store two NSInteger values, as well as a string representation for use with NSLog. I'm running this code in the iOS 4.3 iPad simulator bundled with the latest version of xCode.
For some reason the integer values passed to the initX:Y: constructor gets lost. The code below provides Coordinates2D and some code to print an arbitrary float value in its original form, cast as an int, cast as an NSInteger, and then inside the Coordinates2D object.
You should see, as I do, that the value gets lost inside the Coordinates2D constructor; the 'coords.x' argument in NSLog is printed as a random, large integer indicating its value has been lost in memory.
Can anyone help me see why this happens? I can't see what I'm doing wrong.
Many thanks!
Coordinates2D.h
#import <Foundation/Foundation.h>
#interface Coordinates2D : NSObject {
NSInteger x,y;
NSString *asString;
}
#property (nonatomic) NSInteger x,y;
#property (nonatomic, retain) NSString *asString;
-(void)updateStringRepresentation;
-(id)initX:(NSInteger)x Y:(NSInteger)y;
#end
Coordinates2D.m
#import "Coordinates2D.h"
#implementation Coordinates2D
#synthesize x,y,asString;
-(id)initX:(NSInteger)x_ Y:(NSInteger)y_ {
NSLog(#"coords: %i, %i",x_,y_);
if ((self = [super init])) {
self.x = x_;
self.y = y_;
NSLog(#"Coordinates stored %i as %i",x_,self.x);
[self updateStringRepresentation];
}
return self;
}
/*
-(void)setX:(NSInteger)newX {
x = newX;
[self updateStringRepresentation];
}
-(void)setY:(NSInteger)newY {
y = newY;
[self updateStringRepresentation];
}
*/
-(void)updateStringRepresentation {
self.asString = [NSString stringWithFormat:#"%i,%i",x,y];
}
-(void)dealloc {
[asString release];
[super dealloc];
}
#end
Example of problem:
Coordinates2D *coords = [[Coordinates2D alloc] initX:(NSInteger)(202.566223/200.00) Y:0.0f];
NSLog(#"202.566223/200.00 = %f, as int:%i, as NSInteger:%i, as Coordinates2D:%i",
202.566223/200.00, (int)(202.566223/200.00), (NSInteger)(202.566223/200.00), coords.x);
I read awhile ago that you should never use the property accessor in init methods.
I think you want to change:
#property (nonatomic) NSInteger x,y;
to:
#property (nonatomic, assign) NSInteger x,y;
That should fix the error, as it runs fine when I put it in an xcode project.

Help with a method that returns a value by running another object's method

I have a Class that runs the following method (a getter):
// the interface
#interface MyClass : NSObject{
NSNumber *myFloatValue;
}
- (double)myFloatValue;
- (void)setMyFloatValue:(float)floatInput;
#end
// the implementation
#implementation
- (MyClass *)init{
if (self = [super init]){
myFloatValue = [[NSNumber alloc] initWithFloat:3.14];
}
return self;
}
// I understand that NSNumbers are non-mutable objects and can't be
// used like variables.
// Hence I decided to make make the getter's implementation like this
- (double)myFloatValue{
return [myFloatValue floatValue];
}
- (void)setMyFloatValue:(float)floatInput{
if ([self myFloatValue] != floatInput){
[myFloatValue release];
myFloatValue = [[NSNumber alloc] initWithFloat:floatInput;
}
#end
When I mouse over the myFloatValue object during debugging, it does not contain a value. Instead it says: "out of scope".
I would like to be able to make this work without using #property, using something other than NSNumbers, or other major changes since I just want to understand the concepts first. Most importantly, I would like to know what mistake I've apparently made.
I can see a couple of mistakes:
The line #implementation should read #implementation MyClass
The function setMyFloatValue is missing a closing ] and } —it should read:
- (void)setMyFloatValue:(float)floatInput{
if ([self myFloatValue] != floatInput){
[myFloatValue release];
myFloatValue = [[NSNumber alloc] initWithFloat:floatInput];
}
}
I've just tested it in Xcode and it works for me with these changes.
Why not just set property in interface and synthesize accessors in implementation?
#interface MyClass : NSObject {
float *myFloat
}
#property (assign) float myFloat;
#end
#implementation MyClass
#synthesize myFloat;
#end

In Objective-C, can I declare #property on a c-array of floats?

thing.h
#interface Thing : NSObject
{
float stuff[30];
}
#property float stuff;
#end
thing.m
#implementation Thing
#synthesize stuff;
#end
I get error: type of property 'stuff' does not match type of ivar 'stuff'
I don't want to use an NSArray because I'd have to make the floats into NSNumbers (right?) and that's a pain to do math with.
Update: I've noticed similar answers had guesses and trial answers. While I appreciate the attempts by non-Objective-C folks, I'm hoping for a definitive answer whether it's possible or not.
OK, I have compiled up the following code at it works as expected.
FloatHolder.h
#interface FloatHolder : NSObject {
int _count;
float* _values;
}
- (id) initWithCount:(int)count;
// possibly look into this for making access shorter
// http://vgable.com/blog/2009/05/15/concise-nsdictionary-and-nsarray-lookup/
- (float)getValueAtIndex:(int)index;
- (void)setValue:(float)value atIndex:(int)index;
#property(readonly) int count;
#property(readonly) float* values; // allows direct unsafe access to the values
#end
FloatHolder.m
#import "FloatHolder.h"
#implementation FloatHolder
#synthesize count = _count;
#synthesize values = _values;
- (id) initWithCount:(int)count {
self = [super init];
if (self != nil) {
_count = count;
_values = malloc(sizeof(float)*count);
}
return self;
}
- (void) dealloc
{
free(_values);
[super dealloc];
}
- (float)getValueAtIndex:(int)index {
if(index<0 || index>=_count) {
#throw [NSException exceptionWithName: #"Exception" reason: #"Index out of bounds" userInfo: nil];
}
return _values[index];
}
- (void)setValue:(float)value atIndex:(int)index {
if(index<0 || index>=_count) {
#throw [NSException exceptionWithName: #"Exception" reason: #"Index out of bounds" userInfo: nil];
}
_values[index] = value;
}
#end
then in your other application code you can do something like the following:
** FloatTestCode.h **
#import <Cocoa/Cocoa.h>
#import "FloatHolder.h"
#interface FloatTestCode : NSObject {
FloatHolder* holder;
}
- (void) doIt:(id)sender;
#end
** FloatTestCode.m **
#import "FloatTestCode.h"
#implementation FloatTestCode
- (id) init
{
self = [super init];
if (self != nil) {
holder = [[[FloatHolder alloc] initWithCount: 10] retain];
}
return self;
}
- (void) dealloc
{
[holder release];
[super dealloc];
}
- (void) doIt:(id)sender {
holder.values[1] = 10;
}
The type of the property must match the type of the instance variable it will be stored in, so you could do something like
#interface Thing : NSObject
{
float stuff[30];
}
#property float[30] stuff;
#end
and it should work. I wouldn't recommend it though.
I'm guessing you're looking for something like indexed properties from Delphi. The closest you'll get is something like the following.
#interface Thing : NSObject
{
float stuff[30];
}
- (void) setStuff:(float)value atIndex:(int)index;
- (float) getStuffAtIndex:(int)index;
#end
You can't do it the way you want to do it. You can jump through some hoops and get something similar, e.g. using Daniel's solution, but it's not quite the same thing. The reason you can't do it is that arrays are not lvalues in C. An lvalue is something that can appear on the left-hand side of an assignment. The following code is invalid C:
float stuff1[30], stuff2[30];
stuff1 = stuff2; // ERROR: arrays are not lvalues
As a consequence, you can't declare properties whose types are not lvalues.
Daniel's FloatHolder answer has a major bug (edit: he's now fixed it). It only allocates memory for one float and not for the whole array.
The line:
_values = malloc(sizeof(float));
Should be:
_values = malloc(sizeof(float) * count);
Otherwise it seems to be a good answer. Sorry couldn't work out how to reply directly. (edit: I didn't have the necessary privilege on stackoverflow then.)
Even if you could get that to compile, it wouldn't behave well. 'stuff' would return a float*, and the client would have no idea how long the array way; 'setStuff:' would just change the pointer, and you'd either be pointing to stack-allocated data that would vanish out from under you or heap-allocated data that would leak because it wouldn't know to free it.
I'm not well-versed in Objective-C 2.0, but I'm guessing that the issue might be caused by the fact that a C array is essentially just a pointer to the first element of the array, meaning that the type of float stuff[30] is actually float *, not merely a float.