Can custom property attributes be created in Objective-C just like in VB.NET? For example, in VB.NET you can create the "Browsable" attribute and read it at runtime to determine whether you should display a property or not.
Public Class Employee
<Browsable(True)> _
Public Property Property1() As String
Get
End Get
Set(ByVal Value As String)
End Set
End Property
<Browsable(False)> _
Public Property Property2() As String
Get
End Get
Set(ByVal Value As String)
End Set
End Property
End Class
I would like to do the same in Objective-C, even if it is a fixed attribute that can only be set at compile time and cannot be changed at all.
What I'm trying to do is to add an attribute to properties of my class to determine whether the properties should be serialized or not.
I know the standard Objective-C attributes (readonly, nonatomic, etc.), but those don't help me... unless you have a creative way of using them. I also looked into using C attributes with the __attribute__(("Insert attribute here")) keyword, but C has specific attributes that serve specific purposes, and I'm not even sure you can read them at runtime. If I missed one that can help me, let me know.
I tried using typdef. For example:
typdef int serializableInt;
serializableInt myInt;
and use the property_getAttributes() Objective-C runtime function, but all it tells me is that myInt is an int. I guess typedef is pretty much like a macro in this case... unless I can create a variable of type serializableInt at runtime. Anyhow, here's Apple's documentation on the values you get from property_getAttributes().
The other requirement is that this attribute has to work with NSObject sub-classes as well as primitive data types. I thought about the idea of adding to the class a black lists or white lists as an ivar that would tell me which properties to skip or serialize, which is basically the same idea. I'm just trying to move that black/white list to attributes so it's easy to understand when you see the header file of a class, it's consistent across any class I create and it's less error prone.
Also, this is something to consider. I don't really need the attribue to have a value (TRUE or FALSE; 1, 2, 3; or whatever) because the attribute itself is the value. If the attribute exists, then serialize; otherwise, skip.
Any help is appreciated. If you know for sure that this is not possible on Objective-C, then let me know. Thanks.
If you want to add attribute to property, class, method or ivar, you can try to use github.com/libObjCAttr. It's really easy to use, add it via cocoapods, and then you can add attribute like that:
#interface Foo
RF_ATTRIBUTE(YourAttributeClass, property1 = value1)
#property id bar;
#end
And in the code:
YourAttributeClass *attribute = [NSDate RF_attributeForProperty:#"bar" withAttributeType:[YourAttributeClass class]];
// Do whatever you want with attribute, nil if no attribute with specified class
NSLog(#"%#", attribute.property1)
unless i've missed your point…
i'd recommend declaring a protocol. then using instances of objc objects as variables in your objc classes which adopt the protocol.
#interface MONProtocol
- (BOOL)isSerializable;
- (BOOL)isBrowsable;
/* ... */
#end
#interface MONInteger : NSObject <MONProtocol>
{
int value;
}
- (id)initWithInt:(int)anInt;
#end
#interface MONIntegerWithDynamicProperties : NSObject <MONProtocol>
{
int value;
BOOL isSerializable;
BOOL isBrowsable;
}
- (id)initWithInt:(int)anInt isSerializable:(BOOL)isSerializable isBrowsable:(BOOL)isBrowsable;
#end
// finally, a usage
#interface MONObjectWithProperties : NSObject
{
MONInteger * ivarOne;
MONIntegerWithDynamicProperties * ivarTwo;
}
#end
if you want to share some implementation, then just subclass NSObject and extend the base class.
you'd then have a few variants to write for the types/structures you want to represent.
The deficiency with the other answers I've seen so far is that they are implemented as instance methods, i.e., you need to have an instance already before you can query this metadata. There are probably edge cases where that's appropriate, but metadata about classes should be implemented as class methods, just as Apple does, e.g.:
+ (BOOL)automaticallyNotifiesObserversForKey:(NSString*)key { }
We could imagine our own along similar lines:
+ (BOOL)keyIsBrowsable:(NSString*)key { }
or
+ (NSArray*)serializableProperties { }
Let's imagine our class is called FOOBar, and we want to know whether the baz key is browsable. Without having to create a FOOBar we can just say:
if ([FOOBar keyIsBrowsable:#"baz"]} { ... }
You can do pretty much anything with this technique that can be done with custom attributes. (Except for things like the Serializable attribute which require cooperation from the compiler, IIRC.) The nice thing about custom attributes, though, is that it is easy to distinguish at a glance what is metadata and what is intrinsic to that class's actual functionality, but I think that's a minor gain.
(Of course, you may have to check for the existence of the keyIsBrowsable: selector, just as you'd have to check for the existence of a specific custom attribute. Again, custom attributes have a slight leg up here, since we can tell the .NET runtime to give them all to us.)
I've come across a similar issue whe serializing objects. My solution is to add a #property (nonatomic, readonly) NSArray *serialProperties; which has a custom getter that returns the names (as NSString*) of the properties of this (sub-)class that should be serialized.
For example:
- (NSArray *)serialProperties {
return #[#"id", #"lastModified", #"version", #"uid"];
}
Or in a subclass:
- (NSArray *)serialProperties {
NSMutableArray *sp = [super serialProperties].mutableCopy;
[sp addObject:#"visibleName"];
return sp;
}
You can then easily get all properties and their values via [self dictionaryWithValuesForKeys:self.serialProperties].
You can't add custom properties other than what sdk has provided..
.
But there is a work around to attain your objective...
#interface classTest:NSObject
#property(strong,nonatomic)NSString *firstName;
#property(strong,nonatomic)NSString *lastName;
#property(strong,nonatomic)NSMutableDictionary *metaData;
#end
#implementation classTest
- (id) init
{
self = [super init];
//Add meta data
metaData=[[NSmutableDictionary alloc]init];
//
if( !self ) return nil;
return self;
}
#end
so use the dictionary to add and retrieve meta data...
i hope it helps....
Related
This question already has answers here:
Objective-C: Property / instance variable in category
(6 answers)
Closed 2 years ago.
I've got a form implementation in objective-c and I'd like to extend my widgets (NSButton, NSTextField, etc..) to contain additional string representing their unique identifier string to be used after submit event occur, which trigger generation of json contain all widget id/value pairs.
I've tried using categories to extend NSControl which is the common parent of all those widgets in the following way.
NSControl+formItemSupport.h
-------------------------------
#interface NSControl (formItemSupport)
#property NSString * formItemId;
#end
NSControl+formItemSupport.m
-------------------------------
#implementation NSControl (formItemSupport)
-(NSString *)formItemId {
return self.formItemId;
}
-(void)setFormItemId:(NSString *)formItemId {
self.formItemId = formItemId;
}
in the form.m file I import from NSControl+formItemSupport.m but when I try to set this field in NSButton : NSControl object. However, when I try to set the property formItemId, I get into infinite loop. Perhaps there's another way for extending objc class with variable based property without using inheritance ?
you can
#synthesize formItemId = _formItemId;
//synthesize needs local declaration of _formItemId;
#implementation ExtraWurst {
NSString *_formItemId;
}
but this is done behind the scene for you from Xcode without #synthesize.
Sometime it is still easier to define the use of an internal variable for a property in this way.
apart from that you can and have to change your setter and getter methods in the following way.
-(NSString *)formItemId {
return _formItemId;
}
-(void)setFormItemId:(NSString *)formItemId {
_formItemId = formItemId;
}
this will prevent you from ending up in a loop.
Why?
Because self.formItemId = refers to -(void)setFormItemId:
So you would call the setter inside the setter that will set with the same again and again aka an endless loop.
You can take care of the getter the same way as shown above.
Where to use self.yourProperty then?
You can use self.formItemId anywhere in the class but not inside getter and setter of formItemId.
Correctly mentioned, Instance variables may not be placed in categories.
Meaning if you need such you have to subclass UIControl but that breaks the inheritance of your used UIControls. You would have to subclass all your SpecialUIControls you are using later.
Another solution, you could define a constant in your implementation and go with objective-C runtime functions and associate this constant yourself. Beware because you transform the ObjectModel for all UIControl classes then..
#import "NSControl+formItemSupport.h"
#import <objc/runtime.h>
#implementation UIControl (formItemSupport)
NSString const *key = #"formItemSupport.forItemKey";
-(void)setFormItemId:(NSString *)formItemId {
objc_setAssociatedObject(self, &key, formItemId, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString *)formItemId {
return objc_getAssociatedObject(self, &key);
}
#end
still, its much easier and safer and flexible to subclass your own UIControl instead to extent all subclasses inherited from UIControl.
Why is subclassing easier here?
As you mentioned you want to json later on with the given formItemId per Control you can make use of an archiver / unarchiver design pattern of your subclasses which are nice to jsonify later.
I'd like to define a member in objective C class that can only be read outside the class (public getter). The writing (setter) however shell remain private.
I've read that It's possible to conceal object's setter using the readonly property while exposing the getter using #synthesize syntax but I'm not sure how it works exactly.
Base on this information here's what I did, and I wonder what's happening here under the hood, and if this is the proper way of doing so ?
#interface MyObject : NSObject
//This line suppose to conceal both getter and setter.
#property (readonly) MyCppBaseObject *myCppBaseObject;
- (void)setMyCppBaseObject:(NSString *)SomeInput;
#end
// This line suppose to tell the compiler that the getter is exposed
#synthesize myCppBaseObject = _myCppBaseObject;
#implementation MyObject
-(void)setMyCppBaseObject:(NSString *)SomeInput {
if (someCondition) {
self.myCppBaseObject = new myCppObjectDerive1(...);
} else {
self.myCppBaseObject = new myCppObjectDerive2(...);
}
}
#end
P.S. I've seen a different approach explained in the following link, but I wish to understand the above implementation.
First, you should use the private extension described in the link you provide. That's the correct way to do this.
But to your question, what you've written here is not quite correct.
#property (readonly) MyCppBaseObject *myCppBaseObject;
This line makes a promise to implement -myCppBaseObject. That's all it does. It's just a promise. If you fail to live up to your promise, the compiler will auto-generate (synthesize) one for you using a backing ivar.
- (void)setMyCppBaseObject:(NSString *)SomeInput;
This line is not correct for your purposes. It's making a public setter. But you said you don't want the setter to be public. You could put this in a private extension, however.
#synthesize myCppBaseObject = _myCppBaseObject;
This asks the compiler to create a backing ivar _myCppBaseObject for the property myCppBaseObject. This is the default behavior, however, and so isn't required. (There was a time when it was, but that was a very long time ago.)
-(void)setMyCppBaseObject:(NSString *)SomeInput {
if (someCondition) {
self.myCppBaseObject = new myCppObjectDerive1(...);
} else {
self.myCppBaseObject = new myCppObjectDerive2(...);
}
}
This code is completely incorrect. It is an infinite loop, since self.x =... is syntactic sugar for [self setX:...]. What you mean is:
_myCppBaseObject = ...
You're going to create a lot of headaches having the name of the custom setter be exactly the expected name of the default setter, but with a different type. Don't do this. In theory it could work most of the time, but don't. Especially when there's dot-syntax involved. Especially since one of your objects does not appear to be ARC-compatible (i.e. a C++ object), this is going to really be a trap for really confusing problems. Name your setter differently.
Edit 2: In addition to Kurt's solution, there is one more way to do it. Take a look at the end of this page, just before comments: http://www.friday.com/bbum/2009/09/11/class-extensions-explained/
Edit: It seems class methods in a class category cannot access private members such as ivars and private methods that are implemented through class extensions.
I hope this question is not asked and answered before, but I could not find one as both stackoverflow and Google search spams my browser window with kinds of questions that ask to access an ivar directly from a class method, which is clearly not my intention.
Straight to the problem, I'll provide a piece of code, which summarizes what I'm trying to accomplish:
XYZPerson.h:
#interface XYZPerson : NSObject
#property (weak, readonly) XYZPerson *spouse;
#end
XYZPersonMariage.h:
#interface XYZPerson (XYZPersonMariage)
+(BOOL)divorce:(XYZPerson *) oneOfSpouses;
#end
XYZPersonMariage.m
+(BOOL)divorce:(XYZPerson *)oneOfSpouses
{
XYZPerson *otherSpouse = [oneOfSpouses spouse];
if(otherSpouse != nil)
{
oneOfSpouses->_spouse = nil;
otherSpouse->_spouse = nil;
return true;
}
return false;
}
I first thought that maybe an ivar is not automatically synthesized for a property flagged readonly, but it is indeed synthesized.
So, what paths can I take to get the job done?
Your method +[XYZPerson divorce:] is defined in XYZPersonMarriage.m, which is a different compilation unit than XYZPerson.m where the rest of XYZPerson is implemented.
Because of this, when compiling +divorce:, the compiler doesn't know there's an implicitly synthesized _spouse variable. For all it knows, the property could be backed by a method -spouse that you implemented.
Ways to get around this:
Move the implementation of +divorce into XYZPerson.m.
Don't access ivars directly, but do the work via real methods. They don't have to be part of the usual public interface of the class; they can be exposed via a separate header file that only XYZPersonMarriage.m imports. Search for "Objective-C private method" for more discussion on the pros and cons of that pattern.
I am using CoreData in an iOS application. Everything works fine except for fields marked as Boolean in xcdatamodel that get modeled and NSNumber.
For this kind of fields I want to write some utility method in extended class, but I was wondering where's the best location for writing them or what's the best practice.
In MyManagedObject.h I have:
#interface MyManagedObject : NSManagedObject {
#private
}
#property (nonatomic, retain) NSNumber * mandatory;
#end
Where mandatory is a boolean in data model. This is the generated class from xcode:
#implementation MyManagedObject
#dynamic mandatory;
At this point, for properly using the entity I need to write somewhere some utility wrapper methods, probably in the entity itself, such as:
[myManagedObject mandatoryWrapper:YES];
-(void)mandatoryWrapper:(BOOL)mandatory {
// convert boolean to number
self.mandatory=convertedMandatory;
}
But I am aiming to use the original getter/setter for not generating "confusion":
// setter
myManagedObject.mandatory=YES;
//getter
if(myManagedObject.isMandatory)
but I suppose that rewriting the original methods, will cause some problem later on in the application lifecycle, for example when saving or retrieving in context.
thanks.
If you want a true boolean property, then your are forced to change the name. I would recommend just making the it a property of the class and not the entity because the entity doesn't have to know about them.
In your case, you would need something like:
#property BOOL isMandatory;
-(BOOL) isMandatory{
return [self.mandatory boolValue];
}
-(void) setIsMandatory:(BOOL) boolVal{
self.mandatory=[NSNumber numberWithBool:boolVal];
}
This lets you use convience constructions like:
If (self.isMandtaory)...
self.isMandatory=YES;
Core Data is happy because the entity modeled NSNumber property is still there and works as expected but the human can use the easier to comprehend boolean version.
How do you past values between classes in objective-c?
I'm going to assume the question involves a class, ClassOne, with an instance variable int integerOne, which you'd like to access from another class, ClassTwo. The best way to handle this is to create a property in ClassOne. In ClassOne.h:
#property (assign) int integerOne;
This declares a property (basically, two methods, - (int)integerOne, and - (void)setIntegerOne:(int)newInteger). Then, in ClassOne.m:
#synthesize integerOne;
This "synthesizes" the two methods for you. This is basically equivalent to:
- (int)integerOne
{
return integerOne;
}
- (void)setIntegerOne:(int)newInteger
{
integerOne = newInteger;
}
At this point, you can now call these methods from ClassTwo. In ClassTwo.m:
#import "ClassOne.h"
//Importing ClassOne.h will tell the compiler about the methods you declared, preventing warnings at compilation
- (void)someMethodRequiringTheInteger
{
//First, we'll create an example ClassOne instance
ClassOne* exampleObject = [[ClassOne alloc] init];
//Now, using our newly written property, we can access integerOne.
NSLog(#"Here's integerOne: %i",[exampleObject integerOne]);
//We can even change it.
[exampleObject setIntegerOne:5];
NSLog(#"Here's our changed value: %i",[exampleObject integerOne]);
}
It sounds like you should walk through a few tutorials to learn these Objective-C concepts. I suggest these.