How We store Float value in NSMutableDictionary - ios

- (void)buttonSave:(UIButton *)bttnSave
{
UILabel *lbl = (UILabel *)[self.view viewWithTag:kTagLblText];
[dicStore setValue:lbl.textColor forKey:#"Text Color"];
// fltValue is float type
[dicStore setObject:fltValue forKey:#"font"];
[dicStore setValue:strtextView forKey:#"Text Style"];
[arrStoreDic addObject:dicStore];
}
If We can store this then any one can help me please do

Simply:
dicStore[#"font"] = #(fltValue);
However it's troubling that dicStore is an instance variable that you want to store into an array, which leads me to believe you will end up with an array of the same dictionary, containing the same values.
Instead create a new dictionary each time and store it into the array (unless, of course, other code needs to see this dictionary). The current implementation is very brittle.

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObjects:[NSNumber numberWithFloat:0.5], [NSNumber numberWithFloat:0.7], [NSNumber numberWithFloat:0.2], nil],
nil];
The above code is used to add float values in Dictionary

NSMutableDictionary, NSarray, NSSet and other collection classes accept only objects, and a float variable is a primitive. You have to create a NSNumber object from your float :
NSNumber * floatObject =[NSNumber numberWithFloat:fltValue]
[dicStore setObject:floatObject forKey:#"font"];
Using literals, your code can be simplified to :
-(void)buttonSave:(UIButton *)bttnSave
{
UILabel *lbl = (UILabel *)[self.view viewWithTag:kTagLblText];
dicStore[#"Text Color"] = lbl.textColor;
dicStore[#"font"] = #(fltValue);
dicStore[#"Text Style"] = strtextView;
[arrStoreDic addObject:dicStore];
}
To get back the float value, it's pretty simple :
NSNumber * floatNumber = dicStore[#"font"];
float floatValue = floatNumber.floatValue;

NSDictionary *dict = #{#"floatProperty":[NSNumber numberWithFloat:floatValue]};

Related

How to access Object of Key in NSDictionary with NSNumber instead of NSString in Objective-C

I have a NSDictionary and Int Variable :
mainDic = #{#1:#"1.jpg",#2:#"2.jpg"};
indexpath.row = 2;
I want to access to object for value 2 using indexpath.row like this :
cell.pic.image = [UIImage imageNamed:mainDic[indexpath.row]];
But it doesn't work. ...
mainDic = #{#1:#"1.jpg",#2:#"2.jpg"}; uses NSNumbers for keys in this dictionary.
#1 creates a NSNumber, its just a shortcut for [NSNumber numberWithInt:1].
so your Dictionary looks like this: NSDictionary <NSNumber *, NSString *> *mainDic;.
The row property of NSIndexPath is a readonly integer.
You try to access your NSDictionary with an integer and not with NSNumber as key, the right call should be:
NSNumber *row = [NSNumber numberWithInteger:indexpath.row];
cell.pic.image = [UIImage imageNamed:mainDic[row]];
But I would just use an array, its way simpler to access the images from it.
NSArray *images = #[#"1.jpg",
#"2.jpg",
#"3.jpg"];
cell.pic.image = [UIImage imageNamed:images[indexpath.row]];
Your key should be in the left side, not in right. And also there is typo, I think: #"2,jpg". But should be #"2.jpg".
But in general use an array instead of NSDictionary for this. Because Integer can't be a key, as I remember.
Check your input dictionary. You could entered wrong image name. Replace it with:
mainDic = #{#"1" : #"1.jpg", #"2" :#"2.jpg"};
cell.pic.image = [UIImage imageNamed:[mainDic valueForKey:[NSString stringWithFormat:#"%#", indexpath.row]]];

sort array specified indexes IOS

I' want to filter NSARRAY based on an object named id, I've specific set of Ids that I want to filter and want to be first in NSARRAY.
I stored the following Ids as NSNUMEBR
NSNumber *A = [NSNumber numberWithInt:1122];
NSNumber *B = [NSNumber numberWithInt:1345];
NSNumber *C = [NSNumber numberWithInt:1667];
NSNumber *D = [NSNumber numberWithInt:1223];
NSNumber *E = [NSNumber numberWithInt:1213];
NSNumber *F = [NSNumber numberWithInt:1123];
NSNumber *G = [NSNumber numberWithInt:1555];
NSNumber *H = [NSNumber numberWithInt:1666];
NSNumber *I = [NSNumber numberWithInt:1567];
These are the set of ids that I want to filter and want to be first in my NSARRAY (Can be NSMutableArray for operation)
EDIT 1:
the NSARRAY is basically getting the id object as
Ids = [dict valueForKey:#"id"];
That selective ids are stored in NSNUMBER A to I
It is unclear what you are asking, as indicated by the down votes and comments. But let's see if we can help. I think the following pseudo-code algorithm is what you are asking for:
MutableArray frontItems, rearItems;
for every item in sourceArray
if item["id"] is in the collection of specific IDs
then add item to end of frontItems
else add item to end of rearItems
add rearItems to end of frontItems to give result
Write that in Objective-C and I think you have what you want.
HTH
//Creat array have all item : A->I
NSNumber *A = [NSNumber numberWithInt:1122];
NSNumber *B = [NSNumber numberWithInt:1345];
NSNumber *C = [NSNumber numberWithInt:1667];
NSNumber *D = [NSNumber numberWithInt:1223];
NSNumber *E = [NSNumber numberWithInt:1213];
NSNumber *F = [NSNumber numberWithInt:1123];
NSNumber *G = [NSNumber numberWithInt:1555];
NSNumber *H = [NSNumber numberWithInt:1666];
NSNumber *I = [NSNumber numberWithInt:1567];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:A,B,C,...,I, nil];
for (NSNumber *idx in arr) {
// To do
}

Retrieve values from NSDictionary (which is stored in a NS Mutable Array) from another class

i've stored colors in a dictionary which is added to a nsmutable array.i want to retrieve values of the dictionary from another class based on the keys.thanks in advance
-(NSMutableArray *) GetAllColor
{
UIColor *aminocolor1 = [UIColor colorWithRed:.09 green:.56 blue:.30 alpha:.1];
UIColor *aminocolor2 = [UIColor colorWithRed:1 green:1 blue:1 alpha:.1];
NSDictionary *colordict = [NSDictionary dictionaryWithObjectsAndKeys:
aminocolor1, #"1",
aminocolor2, #"2",
nil];
NSMutableArray *colors = [NSMutableArray arrayWithObjects:colordict, nil];
return colors;
}
You can just chain messages:
NSDictionary* colorDict = [colors objectAtIndex:0];
UIColor *aminocolor = [colorDict objectForKey:#"1"];
Or the same in one line:
UIColor *aminocolor = [[colors objectAtIndex:0] objectForKey:#"1"];
Seeing this piece of code, I have to ask, why do you add the NSDictionary into an NSArray ? Why don't you just return the NSDictionary?
Now the simplest solution:
If you want to get all the NSDictionary from NSArray (if you have more then 1)
for(NSDictionary *dict in colors) {
//do whatever you want with the dictionary (now it's the dict that has the collors)
[dict objectForKey:#"1"] // this is how you get animcolor1.
}
If you want to get just a dictionary at a certain index:
if([colors count] > 0 && [colors count] < yourIndex) { //be smart and perform validations ;)
NSDictionary *dict = [colors objectAtIndex:yourIndex];
//do whatever you want with the dictionary (now it's the dict that has the collors)
[dict objectForKey:#"1"] // this is how you get animcolor1.
}
You can declare that array as a globally to use that array in some other class.

Why aren't these NSString instance variables allocated?

first post here. I was reading through an Objective-C tutorial earlier, and I saw that they had made a couple of NSString instance variables like this:
#implementation MyViewController {
NSString *stringOne;
NSString *stringTwo;
NSString *stringThree;
NSString *stringFour;
NSString *stringFive;
}
And then simply used them in ViewDidLoad like this:
- (void)viewDidLoad
{
[super viewDidLoad];
stringOne = #"Hello.";
stringTwo = #"Goodbye.";
stringThree = #"Can't think of anything else to say.";
stringFour = #"Help...";
stringFive = #"Pheww, done.";
}
How have they done this without instantiating the string? Why does this work? Surely you'd have to do something like stringOne = [NSString stringFromString:#"Hello."]; to properly alloc and init the object before you could simply do stringOne= #"Hello.";.
Sorry if this a dumb question, but I find these little things throw me.
Thanks,
Mike
From the Apple String Programming Guide:
Creating Strings
The simplest way to create a string object in source code is to use the Objective-C #"..." construct:
NSString *temp = #"Contrafibularity";
Note that, when creating a string constant in this fashion, you should use UTF-8 characters. Such an object is created at compile time and exists throughout your program’s execution. The compiler makes such object constants unique on a per-module basis, and they’re never deallocated. You can also send messages directly to a string constant as you do any other string:
BOOL same = [#"comparison" isEqualToString:myString];
String constants like #"Hello" are already allocated and initialized for you by the compiler.
Just remember this basic thing:-
NSString *string = ...
This is a pointer to an object, "not an object"!
Therefore, the statement: NSString *string = #"Hello"; assigns the address of #"Hello" object to the pointer string.
#"Hello" is interpreted as a constant string by the compiler and the compiler itself allocates the memory for it.
Similarly, the statement
NSObject *myObject = somethingElse;
assigns the address of somethingElse to pointer myObject, and that somethingElse should already be allocated and initialised.
Therefore, the statement: NSObject *myObject = [[NSObject alloc] init]; allocates and initializes a NSObject object at a particular memory location and assigns its address to myObject.
Hence, myObject contains address of an object in memory, for ex: 0x4324234.
Just see that we are not writing "Hello" but #"Hello", this # symbol before the string literal tells the compiler that this is an object and it returns the address.
I hope this would answer your question and clear your doubts. :)
actually this can be said "syntactic sugar". there are some other type of NS object that can be creatable without allocation or formatting.
e.g:
NSNumber *intNumber1 = #42;
NSNumber *intNumber2 = [NSNumber numberWithInt:42];
NSNumber *doubleNumber1 = #3.1415926;
NSNumber *doubleNumber2 = [NSNumber numberWithDouble:3.1415926];
NSNumber *charNumber1 = #'A';
NSNumber *charNumber2 = [NSNumber numberWithChar:'A'];
NSNumber *boolNumber1 = #YES;
NSNumber *boolNumber2 = [NSNumber numberWithBool:YES];
NSNumber *unsignedIntNumber1 = #256u;
NSNumber *unsignedIntNumber2 = [NSNumber numberWithUnsignedInt:256u];
NSNumber *floatNumber1 = #2.718f;
NSNumber *floatNumber2 = [NSNumber numberWithFloat:2.718f];
// an array with string and number literals
NSArray *array1 = #[#"foo", #42, #"bar", #3.14];
// and the old way
NSArray *array2 = [NSArray arrayWithObjects:#"foo",
[NSNumber numberWithInt:42],
#"bar",
[NSNumber numberWithDouble:3.14],
nil];
// a dictionary literal
NSDictionary *dictionary1 = #{ #1: #"red", #2: #"green", #3: #"blue" };
// old style
NSDictionary *dictionary2 = [NSDictionary dictionaryWithObjectsAndKeys:#"red", #1,
#"green", #2,
#"blue", #3,
nil];
for more information, see "Something wonderful: new Objective-C literal syntax".

Add values in NSMutableDictionary in iOS with Objective-C

I'm starting objective-c development and I would like to ask the best way to implement a list of keys and values.
In Delphi there is the class TDictionary and I use it like this:
myDictionary : TDictionary<string, Integer>;
bool found = myDictionary.TryGetValue(myWord, currentValue);
if (found)
{
myDictionary.AddOrSetValue(myWord, currentValue+1);
}
else
{
myDictionary.Add(myWord,1);
}
How can I do it in objective-c? Is there equivalent functions to the above mentioned AddOrSetValue() or TryGetValue()?
Thank you.
You'd want to implement your example along these lines:
EDIT:
//NSMutableDictionary myDictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *myDictionary = [[NSMutableDictionary alloc] init];
NSNumber *value = [myDictionary objectForKey:myWord];
if (value)
{
NSNumber *nextValue = [NSNumber numberWithInt:[value intValue] + 1];
[myDictionary setObject:nextValue forKey:myWord];
}
else
{
[myDictionary setObject:[NSNumber numberWithInt:1] forKey:myWord]
}
(Note: you can't store ints or other primitives directly in a NSMutableDictionary, hence the need to wrap them in an NSNumber object, and make sure you call [myDictionary release] when you've finished with the dictionary).
The other answers are correct, but there is more modern syntax for this now. Rather than:
[myDictionary setObject:nextValue forKey:myWord];
You can simply say:
myDictionary[myWord] = nextValue;
Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).
Yep:
- (id)objectForKey:(id)key;
- (void)setObject:(id)object forKey:(id)key;
setObject:forKey: overwrites any existing object with the same key; objectForKey: returns nil if the object doesn't exist.
Edit:
Example:
- (void)doStuff {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:#"Foo" forKey:#"Key_1"]; // adds #"Foo"
[dict setObject:#"Bar" forKey:#"Key_2"]; // adds #"Bar"
[dict setObject:#"Qux" forKey:#"Key_2"]; // overwrites #"Bar"!
NSString *aString = [dict objectForKey:#"Key_1"]; // #"Foo"
NSString *anotherString = [dict objectForKey:#"Key_2"]; // #"Qux"
NSString *yas = [dict objectForKey:#"Key_3"]; // nil
}
Reedit: For the specific example there exists a more compact approach:
[dict
setObject:
[NSNumber numberWithInteger:([[dict objectForKey:#"key"] integerValue] + 1)]
forKey:
#"key"
];
Crazy indentation for readability.

Resources