How to iterate over the properties of my models in objective c? - ios

I want to iterate over the properties of my models in Objective-C. I tried this. Created PropertyUtil class with method classPropsFor:(Class)klass. Please find the attachment. Used objc/runtime.h. The code which I got from the net. In my viewcontroller I am doing this. [PropertyUtil classPropsFor:[self.user class]];. self.user is User model class. What I want to know is how can i iterate over the properties of my models, let's username, password and those values.

You may want to manually list all properties your model has.
Just add a method to your model:
+(NSArray*) propList {
return #[#"prop1", #"prop2"];
}
Then just use key-value coding to get the value
[someObject valueForKey:#"prop1"];
That's pretty straight and simple way if you wish to avoid Obj-C meta functions. Since you add your properties manually anyway, you may also add them in your list as well.
That's of course, if you don't have a large amount of models already and you wish do them all at once.

Related

Managing an enum within a PFObject - iOS Swift/Parse

I'm new to Parse and Swift.
I have an app where people play against each other.
I want to create an activity feed where game results, cheers, heckles (anything really) can show up in a list.
My thought is to create an Activity class that subclasses PFObject and I'd like to have an enum ActivityType to determine what kind of Activity is being created.
Can I set up the Activity object in Parse and the PFObject in Swift so that each Activity is set up with the correct ActivityType?
My thinking is that I need a "Type" column in Parse that's just a number and an init method that reads that number and sets the correct type.
Does that sound about right?
Thanks
You could use a type column in parse, though I'd expect each of your different kinds of feed item to be different classes in parse as they all have different data and relationships, so you could use the class type (name).
In either case this is just a way to identify the type coming from the server. Once you have that you want an organised and common approach to displaying the feed items. To do that you should have a protocol which defines what a feed item needs to provide in order to be displayed on the feed. Then you have a set of classes, each conforming to that protocol, and each dealing with one of the different types of feed item to 'mutate' them into the common format for display.
Using an enum in your app would work, but it could lead you to have one big switch statement dealing with everything. So long as you just use the enum and switch to deal with deciding which class to create to handle the feed item then your code should be well structured.
I've solved this problem. It was 'free' functionality from Parse. I think first of all, you should consider subclassing PFObject (for many reasons). Once you do this, all you have to do is add the enum as a property to your subclass. It's taken care of automatically by Parse.
Parse knows how to convert to NSNumber and vice versa for an enum, no need to worry about that.
Note, in your .m file:
#implementation MyParseObjectSubclass
#dynamic aPropertyIWantPersisted; // declare your properties as dynamic to be managed by Parse
#synthesize aLocalTransientProperty; // if you have transient properties that you don't want persisted to the server.
+ (void)load
{
[self registerSubclass];
}
+ (NSString*)parseClassName
{
return "MySubclass";
}
#end

Writing an SDK in Objective-C

Basically, I want to make api calls using an SDK I am writing.
I have the following classes:
Car
CarData (stores input values needed to create a car like model, make, etc)
Basically to create a car I do the following:
[Car carWithData: cardata onSuccess: successHandler onError: errorHandler]
that basically is a factory method that creates instance of Car after making an API call request and populating the new Car class with the response and passes that instance to the successHandler.
So "Car" has the above static method to create that car, but also has non-static methods to edit, delete cars (which would make edit, delete API calls to the server)
So when the Car create static method passes a new car to the successHandler by doing the following:
successHandler([[Car alloc] initWithDictionary: dictionary)
The success handler can go ahead and use that new car to do the following:
[car update: cardata]
[car delete]
considering the new car object now has an ID for each car that it can pass to the update and delete API calls.
My questions:
Do I need a cardata object to store user inputs or can I store them in the car object that would also later store the response from all of the api calls?
How can I improve this model?
With regards to CarData, note that there might be different inputs for the different API calls. So create function might need to know model, make, etc, but find function might need to know the number of items to find, the limit, the start id, etc.
First, names are very important in building an SDK. Your names are a bit confusing. CarData sounds very much like it is related to an NSData. The typical name for "a class that holds information about another class" is a "descriptor." So, I would call this CarDescriptor. See UIFont and UIFontDescriptor for inspiration.
Next, your carWithData:onSuccess:onError: very much sounds like it should return a Car, but it appears to be void. I recommend the following:
+ (void)createCarWithDescriptor:(CarDescriptor *)descriptor
completion:(void (^)(Car *car, NSError *error))completion;
It is preferred to have a single completion block, rather than two. Do not prefix completion handlers with on.
The CarDescriptor class should help you with your searching question as well, but it should not include things like limits. You should wrap that in a CarSearchRequest (or possibly just a CarSearch). See NSFetchRequest for inspiration. Whether you pass a CarDescriptor or need a full predicate depends on how your service manages searches. (Of course, you could always have code that converts a CarDescriptor into a predicate.) Again, look at how UIFontDescriptor is used to search for fonts for inspiration.

Ruby Rails - Go through Array & Save Each Value As A Unique Variable

My array contains a varying amount of objects. I need to iterate through the array and save each object id as a unique variable. Given the amount of objects within the array will vary, how should I do this?
"items"=>[{"id"=>"B00668BTCI"}, {"id"=>"B0041KJSL2"}]
I need to save the information to a new object that can support up to 16 IDs. #object.id_one, #object.id_two, etc...
The suitable way to save your data all depends upon how you want to reference it or access it later. Meta-programming is interesting and fun, but may be overkill depending upon your needs. You will need to determine that after looking at the choices. An alternative way is in an array:
array_of_ids = items.map(&:values).flatten
Or
array_of_ids = items.map { |item| item["id"] }
Then all of the IDs are in the array array_of_ids and becomes, in your example:
["B00668BTCI", "B0041KJSL2"]
Accessible by:
array_of_ids[0] # first id
array_of_ids[1] # second array
...
You need to do some meta-programming here...
Here is a post for you, it has an answer (by Chirantan) that shows how to create instance variables dynamically.
Hope this helps.
EDIT
Just in case you get interested to learn more, I have also found a good article about creating methods dynamically, check it out.
Dynamically adding class methods in Ruby by Ryan Angilly

Get NSManagedObject attribute validation regular expression

In my data model, some of the attributes have regular expressions used for data validation. There are places in my code that I would like to use those same regular expressions.
In the interest of keeping my common regular expressions in one place, I was hoping either to set these regexes in code or to retrieve them from the data model in code.
Is there a way to do this?
I want to access the Reg. Ex. property, shown below, in code.
From a NSEntityDescription you can get its attributes with the method attributesByName. Then you can use the NSPropertyDescription methods validationPredicates and setValidationPredicates:withValidationWarnings:. I assume that a predicate is created under the hood when you set the validation regex in your datamodel file...
I am not completely sure about this, but I think you can only set these values when you are creating your core data model, not once you have your core data stack set up. Is that what you want to do?
Absolutely. Everything you do in the model editor can be done or modified in code by manipulating your NSManagedObjectModel object.
Locate where the model is retrieved in your core data stack setup (maybe in your app delegate). Before returning the model, modify it in code, using constants you can #define in a central include file.
Read all about the object model's API here. More precisely, you set the model's entities after modifying an entity description, by changing the validationPredicates of one of its attributes.
I marked e1985's answer as accepted, since that's the answer that led me here. Here's the code I used to get the predicate. It's in a category for NSEntityDescription.
- (NSPredicate*)getValidationPredicateForAttribute:(NSString*)attributeName
{
NSAttributeDescription* emailAttribute = [self.attributesByName objectForKey:attributeName];
NSArray* validationPredicates = [emailAttribute validationPredicates];
if(validationPredicates.count > 0)
{
return [validationPredicates objectAtIndex:0];
}
return nil;
}

iOS - Saving NSMutableArray to iPhone

I'll ask in the form of a hypothetical, which might make it easier for me to explain.
I have a class called Person, and in this has three fields:
NSString *name;
NSDate *dateOfBirth; and
NSMutableArray *friends.
An example object is this:
name = "John Smith"
dateOfBirth = 01/04/1985
friends = "Simon Scott"; "Jennifer Lane"; "Mary Firth"
Once the user has filled the NSMutableArray with the data they want, what would be the best way to save this data to the iPhone? I would anticipate that there could be up to 100 instances of the Person object, and all that will be required is the displaying of this data in a UITableView and giving the user the ability to add and remove entries at their will.
I have seen multiple suggestions on this site, which include NSDictionaries and using the writeToFile method, but before I research one of these, I was hoping someone could point me in the right direction? I would like to ensure that I'll be using the easiest and most appropriate method that's out there.
Many thanks.
Please take a look at the Property List Programming Guide. As long as you stick with a core set of object types for your data, you can write and read your data from a file or URL in one line, like this:
[people writeToURL:someURL atomically:NO];
The types you've mentioned in your question (strings, dates, arrays, dictionaries) can all be written to a property list.
#Achiral,
It really depends on what you want to do with the data and how concerned you are with the flexibility of your code.
However, my recommendation would be to use CoreData to make an SQLlite database and make a 'Person' entity with the properties that you list above. I don't know if you are familiar with CoreData, but it is highly optimized on iOS and is pretty easy to use, since it has a pretty simple 'fill in the blanks' style form for creating the data models. You should also note that CoreData is a well accepted and supported way to store data in an iOS and OS X app.
I hope this helps.

Resources