开发者

custom delegate in objective c

开发者 https://www.devze.com 2023-03-01 18:56 出处:网络
i\'ve done a class like this: testClass <UIAccelerometerDelegate> and i implement the methods of delegate.

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 sha开发者_如何学运维redAccelerometer];
[a setDelegate: t];

and in dealloc i release t.

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


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号