Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define and implement properties in protocol

I want to define one protocol with few properties and need to use those properties in another NSObject subclass. Please give me link or example code. I need that to work with 10.5.

Thanks PLEASE CHECK THE FOLLOWING SAMPLE CODE

@protocol MyProtocol
@property (nonatomic, readonly) id someObject;
@property (nonatomic, getter=isAlive) BOOL alive;
@end

#import "MyProtocol.h"
@interface MyCustomClass : NSObject <MyProtocol>{

}
@end

#import "MyCustomClass.h"
@implementation MyCustomClass
@synthesize someObject,alive;

/*
- (id)someObject {
    return nil;
}

- (BOOL)isAlive {
    return YES;
}

- (void)setAlive:(BOOL)aBOOL {
}
*/
@end

**Added: Compling code with x86_64 architecture works fine. But error if i'll change the architecture to i386, then i am getting following warnings:

MyCustomClass.m:13: error: synthesized property 'someObject' must either be named the same as a compatible ivar or must explicitly name an ivar

 error: synthesized property 'alive' must either be named the same as a compatible ivar or must explicitly name an ivar

I just want to know why it is working in x86_64 with @synthesize and not in i386.**

like image 666
AmitSri Avatar asked Jul 31 '10 11:07

AmitSri


People also ask

Can we define property in protocol?

You can have properties in a protocol, provided every class that conforms to your protocol have a corresponding @synthesize for that property, or provide a getter and setter. But with a class category you generally can't add instance variables to a class.

Can we define properties in protocol Swift?

In Swift, protocols can't specify access control to the properties they declare. If a property is listed in a protocol, you have to make conforming types declare those properties explicitly.

What is protocol implementation?

A protocol implementation is a NET_ProtoImpl struct defined in ns/lib/libnet/mkgeturl. h. This struct simply consists of four function pointers; an initialization function, a processing function, an interrupt function, and a cleanup function.


2 Answers

@property just says to the compiler that the class is expected to define the methods to match that property.

@protocol MyProtocol
@property (nonatomic, readonly) id someObject;
@property (nonatomic, getter=isAlive) BOOL alive;
@end

Anything implementing that protocol will now need to have

- (id)someObject;
- (BOOL)isAlive;
- (void)setAlive:(BOOL)aBOOL;
like image 184
Joshua Weinberg Avatar answered Sep 19 '22 11:09

Joshua Weinberg


I think the things you're dealing with are primarily side effects of the introduction of Objective-C 2.0. It lets you do things like declare properties without also defining instance vars. But (as you have discovered), it is only x86_64 and post-10.5 compatible.

like image 45
Ben Mosher Avatar answered Sep 19 '22 11:09

Ben Mosher