Domanda

I'm kind of lost in this subject of object properties. The Idea of my app is to have a number of functions in the ViewController and store them via pointer to function (*attack) in a Class (enemy). The Problem is passing objects by reference to this function.

two classes: enemy and player (NSObjects)

enemy.h

@property void (*attack)(Class *enemy, Class *player, int); // synthesized

ViewController.h

@interface ViewController : UIViewController {

player *player1;
enemy *monster1;
}

@property enemy *monster1;
@property player *player1;

ViewController.m

void attack1(enemy *attacker,player *target, int x) {

target.health = target.health - x;
NSLog(@"%i",target.health);
}

@implementation ViewController
@synthesize player1;    
@synthesize monster1;

- (void)viewDidLoad {

[super viewDidLoad];

self.player1 = [[player alloc] init];
self.monster1 = [[enemy alloc] init];

player1.health = 100;

The follwing two statements don't work:

monster1.attack = attack1;              //Error 1 (yellow)
monster1.attack(&monster1,&player1,20); //Error 2 (red)

Error 1 says: "Incompatible pointer types assigning to 'void (*)(__unsafe_unretained Class*, __unsafe_unretained Class*, int)' from 'void (enemy *_strong, player *_strong, int)'"

Error 2 says: "Passing 'player *__strong *' to parameter of type '__unsafe_unretained Class *' changes retain/release properties of pointers" (2 times)

I have tried permutations of putting __unsafe_unretained into the function in enemy.h or (nonatomic, assign) after @property but nothing seems to work.

È stato utile?

Soluzione

Error 1: Class is the type of classes not the type of any object instances. If you want to accept an instance of any class you can use id or NSObject * for the type.

Error 2: monster1 is a variable of type enemy * (Note: classes by convention start with an uppercase letter, use Enemy) and will contain a reference to an instance of type enemy. The expression &monster1 evaluates to the address of the monster1 and is of type enemy ** - a reference to a reference to an enemy. You should not be using the & operator.

There are probably other errors & design issues. You appear to have some misunderstandings about Objective-C, classes, objects, references and coding conventions; it might be a good idea to do some studying.

HTH

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top