1

i've done a class like this:

testClass <UIAccelerometerDelegate>

and i implement the methods of delegate.

Then in other class where i want this delegate i've done:

testClass *t = [[testClass alloc]init];
UIAccelerometer *a = [UIAccelerometer sharedAccelerometer];
[a setDelegate: t];

and in dealloc i release t.

It works, but is this the right way to write a general delegate?

Vladimir
  • 170,431
  • 36
  • 387
  • 313
bov
  • 11
  • 1

2 Answers2

0

In general that is right, but you need to be careful when deciding to retain or assign the delegate to avoid circular references. I have been bit by this before. Here is a good post talking about it and some nuances to be aware of: Why are Objective-C delegates usually given the property assign instead of retain?

Community
  • 1
  • 1
ljkyser
  • 999
  • 5
  • 9
  • `UIAccelerometer` is apple's class, so the OP doesn't have to worry about any delegate retain/release issues. This answer has nothing to do with the question. – kubi Apr 29 '11 at 14:45
  • Why the down vote? Did you read the whole question? He is asking if in **GENERAL** that is the right way to use delegates, not just with the `UIAccelerometer` class. If he is releasing it in dealloc, he is retaining it, therefore it is relevant. Read the whole question next time... – ljkyser Apr 29 '11 at 14:51
  • He was asking how to set delegates for other objects, not how to deal with delegates properties of his own objects. The OP's `testClass` is an iVar of his class, so it must be retained and released. – kubi Apr 29 '11 at 15:09
0

That is one way to write a delegate. An easier way would be to implement the delegate methods in the class in which you created your testClass instance and set the UIAccelerometer delegate property to self.

Also, just a consistency note, it's proper for class names to start with a capitalized letter, so your class should be called TestClass.


Also, you do need to set the UIAccelerometer delegate property to nil when you deallocate the delegate object.

kubi
  • 48,104
  • 19
  • 94
  • 118