In my iPhone App.
Problem: When I am trying to get the value from dictionary in model class it is giving me the nil values.
Why this is happening, is this the memory management issue ?
I did this,
I am passing NSDictionary, from my viewController to NSMutableArray Category and from that I am passing it to my Modelclass.
If you want to see the coding,
In my ViewController.m file
[arrayNews convertToNewsArticles];
In my NSMutableArray category I am calling method convertToNewsArticles.
for(NSMutableDictionary *dictionary in self) {
NewsArticle *newsArticle=[[NewsArticle alloc] initWithDictionary:dictionary];
[arrayConverted addObject:newsArticle];
}
I am talking about this dictionary that I am passing.
Here is my Model class
-(NewsArticle*)initWithDictionary:dictionary{
self.title=dictionary[#"title"];
self.author=dictionary[#"author"];
self.urlString=dictionary[#"url"];
return self;
}
Update:
I solved by using IAModelBase class on GitHub.IAModelBase
If it is subclass of NSMutableArray then you can add object like,
[self addObject:newsArticle];
in your for loop and return self will return your final mutable array and you can use it as per desired need!
And refer Apple documentation for more detail. You have to implement some mandatory methods if you want to subclass the NSMutableArray.
When I was trying to convert NSDictionary Objects to Model Objects.
I could not pass the whole dictionary to Model class. Like mentioned in the question.
But instead I used,
IAModel classes
Read the readme file.
Also see the 1st Issue,it is solved.
Pull Issue
Related
I have an initializer that takes an array of Strings as a parameter. Rather than re-write the class and risk breaking things, I'd prefer to feed the initializer what it wants.
I'm trying to extract NSStrings from NSManagedObjects stored in an NSOrderedSet.
Here's what I've tried:
let soundsToPlay = sequenceToPlay.sounds as NSOrderedSet
for element in soundsToPlay {
// this prints out the object in console
print("\(element)")
// this, doesn't give me accessors for the sound object
// print("\(element.fileName)")
}
I'm missing something basic, but I'm not sure what. How would I enumerate the objects in an NSOrderedSet and extract the value of the attributes for the entities contained within the set?
I would suggest reading the documentation on KVC (Key Value Coding) as you can write this as one line of code:
let filenameArray = soundsToPlay.valueForKey("fileName").array()
The call to valueForKey will return an NSOrderedSet of the string and then you can convert that to an array with a call to array()
I figured it out. I was missing a step:
let soundsToPlay = sequenceToPlay.sounds as NSOrderedSet
for element in soundsToPlay {
// I have to tell the compiler what type of thing my thing is
let whatIWantToAccess = element as! MyObjectINeedAccessorsFor
print("\(whatIWantToAccess.fileName)")
}
Thats probably because compiler thinks that "element" is instance of NSManagedObject and it does not have fileName , try explicit type-casting , something like
for element: YourClass in soundsToPlay
I am importing a json where the objects have many array attributes such as images:
"images": [
"model1.jpg",
"model2.jpg"
],
"models": []
"one model",
"another model",
"third model"
]
Currently I just do:
[ExampleObject MR_importFromArray:objectArrayFromJson];
but these arrays break this auto import since it can't auto fit NSArray to NSData (the binary from when setting the model up in Xcode).
Is there anyway to modify the Model class files (like custom setters/getters) so the MagicalRecord can import my array and store it in the entitys´ attribute and when I retrieve it I get an NSArray in return?
I solved this myself after some research and I want to share it to whoever might get stuck with same problem.
My problem was that I wanted to save an NSArray into an entity attribute of type NSData. To be able to do this with MagicalRecord I needed to implement a method in my NSManagedObject m-file like this:
- (BOOL) importImages: (id) array {
NSData *imagesData = [NSKeyedArchiver archivedDataWithRootObject:array];
self.images = imagesData;
return YES;
}
so import<;attribute-name without ;> the method must be called.
EDIT:
According to this page you return YES if your code process the data. Return NO if you want MagicalImport to continue processing the attribute and use the default import routines.
I am trying to write a method which will allow me to keep the order of my NSMutableDictionary keys when they are being inserted into the data structure. I know that the NSMutableDictionary works of a hash map, hence not maintaining specific order.
So I need to somehow keep track of the keys which are being inserted into the dictionary, and when retrieving the values from the dictionary, the keys are to be printed(key values) in this same order as when originally inserted. The keys which are inserted into the dictionary are alphanumeric. They just need to be printed out in the same order as when inserted into the NSMutableDictionary.
Can this be achieved? I would like to remain using the NSDictionary Data Structure.
NSDictionary (and all its relations) are unordered collections so to "keep its order" makes no sense as there is no order.
If you are wanting to retrieve objects in a specific order then you need to be using an NSArray. (Or NSOrderedSet if uniqueness of hashes is important).
Simple and naive option
If you have a dictionary structure of...
{
key1:value1,
key2:value2,
key3:value3,
//and so on
}
Then you might be better using something like...
[
{
key1:value1
},
{
key2:value2
},
{
key3:value3
}
]
// i.e. an array of dictionaries
More code but much better option
Or you could create a new collection class as a subclass of NSObject.
In the class you could have something like...
- (void)addObject:(id)object forKey:(id)key
{
self.dictionary[key] = object;
[self.array addObject:key];
}
And...
- (id)objectForKey:(key
{
return self.dictionary[key];
}
And...
- (id)objectAtIndex:(NSUInteger)index
{
return self.dictionary[self.array[index]];
}
And even...
- (void)removeObjectForKey:(id)key
{
[self.dictionary removeObjectForKey:key];
[self.array removeObject:key];
}
You could even make it conform to fast enumeration so you can do...
for (id object in mySuperSpecialCollection) {
}
and make it dispense objects in the order of the array.
Can this be achieved? I would like to remain using the NSDictionary Data Structure.
No. When using instances of NSDictionary the actual class is private. As often with class clusters, it's not possible to subclass NSDictionary and use derived functionality (storing key value pairs).
The best way to go is to set up your own data structure, maybe using an NSOrderedSet and an NSDictionary in conjunction.
My usecase here is, I need to search for a string within a set of strings(say synonyms). If I find the relevant search-word within the set of strings, then I will display the set of values associated with that set of strings. I am currently thinking of implementing it as a Map, but not sure, if that's even possible.
I am confused about the best data-structure that can be used in this scenario?
Thanks for the help.
EDIT
Replaced Array with Set as it made more sense
Scenario:
Set-1 = {jug,jar,bottle,cup}
Set-2 = {"Store water", "Store Juice", "Store Coffee"}
For any input I receive from either jug,jar,bottle,cup, I should return the properties associated with it from Set-2. In simple words, I need to return whole of Set-2 when any word from Set-1 matches. Hopefully, this will make my question clear.
you can subclass NSObject for that kind of behaviour.
#interface Synonyms : NSObject
#property NSArray *strings;
#property NSArray *values;
-(NSArray *)searchForWord:(NSString *)searchWord;
#end
#implementation Synonyms
-(NSArray *)searchForWord:(NSString *)searchWord{
BOOL found=NO;
//add code to search for that search term in strings array
if(found)
return self.values;
else
return nil;
}
#end
so, first create all these synonyms instances and store them in NSArray.
Assign strings and values array to each instance.
When user enters search-word, call searchForWord function for each element of array.
If found ,it returns not nil object.else no synonym.
PART 2:
If you are looking for below kind of behaviour, example below
Dictionary myDic;
myDic.Add("car", "automobile");
myDic.Add("car", "autovehicle");
myDic.Add("car", "vehicle");
myDic.Add("bike", "vehicle");
myDic.ListOSyns("car") // should return {"automobile","autovehicle","vehicle" ± "car"}
// but "bike" should NOT be among the words returned
Then you can use NSDictionary,
NSDictionary *dictionary =#{#"car":#[#"automobile",#"autovehicle",#"vehicle"],#"bike":#[#"vehicle"]};
NSArray *values =[dictionary objectForKey:#"search-term"];
if(values==nil)
//no result
else
return values;
So my JSON request should look something like:
{
"MyDictionary" : ["some values"],
"RegularValue" : "regularValue",
}
So what I currently have done is:
NSDictionary *myDict = #{#"Blah" : #"1", #"Yadayada" : #"2"};
NSDictionary *jsonDict = #{"MyDictionary" : myDict, "RegularValue" : "someValue"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&error];
So this works fine. The problem I have is, instead of manually creating MyDictionary, what I want to do is use a custom sublcass of NSObject and serialize that to JSON. I basically have to manually create the NSDictionary for the properties of my custom NSObject and put that in the NSJSONSerialization method. But I was wondering if there was a better way to do this? Thanks.
maybe this can help JLCustomClassDisassembler.
it iterates the custom object to get the properties. this will give you dictionary/array then just use sbjson/jsonkit or what ever you prefer to construct your json string.
To achieve this you would need to create your own custom NSObject class with attributes and more and still have a custom method to serialize the object, similar to the way toString works on java, on Objective-C you would need to implement
- (NSString *)description
on your method and then return the serialized object.
on this method you could read all the attributes of the current object and then somehow serialize them, this thread presents a nice sample code to read all the attributes of a certain Object
Get an object properties list in Objective-C