iOS converting value in NSDictionary with (int) fail - ios

I had a NSDictionary contains 2 key/value pairs:
NSDictionary *dic = #{#"tag":#2, //NSNumber
#"string":#"someString"}; //NSString
NSLog(#"%i",(int)[dic objectForKey:#"tag"]); //print out 34
NSLog(#"%i",[dic objectForKey:#"tag"] intValue]); //print out 2
Why does "converting id value to int with (int)"get me the wrong result but not the other way? are they in different levels of conversion?

Why does "converting id value to int with (int)"get me the wrong result but not the other way? are they in different levels of conversion?
id is a pointer type. id pointers point to Objective-C objects in memory. By casting id to (int), you are merely reinterpreting (some of) the pointer's bit pattern as an int, which is quite meaningless. You have to call the proper conversion methods of NSString and NSNumber if you want to reliably get the primitive values out of the Objective-C object.
If you ever seemingly get the "correct" value of 2 in the case of pointer-casting with NSNumber, that may be because the Objective-C runtime makes use of an optimization technique called tagged pointers, whereby small objects are not really created and allocated, but their semantics (the number's bits which the NSNumber object stores) is stuffed into the unused bits of the pointer.

#2 is not an int but a NSNumber you can't cast an NSNumber into an int. You have to use intValue method to get the correct result.

The method objectForKey: returns a pointer to the NSNumber object #2, not the value stored in the object itself. So you're typecasting the pointer, not the value 2. In the last line you don't typecast the object but you access a property called intValue which returns the value of the object expressed as an int.

NSDictionary contains Object with Key value pairs,but you passed int(#2) into object
NSDictionary *dic = #{#"tag":#2, //NSNumber
#"string":#"someString"};
so Change int to NSNumber like
NSDictionary *dic = #{#"tag":[NSNumber numberWithInt:2];,#"string":#"someString"};
and you can get it..
int number = [[dict objectForKey:#"tag"] intValue];

Related

Getting an error while adding a integer to array object at index (objective c)

while adding a integer to object at index of an array, I am getting an error of "arithmetic on pointer to interface id which is not a constant size for this architecture and platform", didn't know how to resolve it.
Please help.
my code is -
if (arrayTotalAmount.count>0) {
int sum = 0;
for (int i = 0; i<=arrayTotalAmount.count; i++) {
sum = (sum+[arrayTotalAmount objectAtIndex:i]);
}
In 4th line I am getting that error.
Thanks
Objective C array only accepts NSObject type. That means it is impossible to insert a primitive value into an NSArray. You are getting an error because objectAtIndex method returns a pointer which points to that NSObject, the arithmetic operations are still valid on pointers but the thing is that the size of a pointer as integer (32bit, 64bit) may differ on device. So one of the solution is typecasting the pointer sum+(int)[arrayTotalAmount objectAtIndex:i] which makes no sense in your case.
The solution you are looking for is probably sum+[[arrayTotalAmount objectAtIndex:i] intValue] or similar. Assuming that array contains NSNumber objects. If the object inside an array is not an NSNumber then your app will fail in runtime showing an error indicating that an object X does not have a method called intValue in which case you will need to figure how to convert object X to your int.
You just need to convert your array object to integer and then add it will work for you.
if (arrayTotalAmount.count>0) {
int sum = 0;
for (int i = 0; i<=arrayTotalAmount.count; i++) {
sum = (sum+[[arrayTotalAmount objectAtIndex:i] intValue]);
}

IOS/Objective-C: Get Number from JSON

I have a JSON dictionary that contains what I will call an integer (in mathematics) i.e. 1.
I would like to save this number to a core data attribute that is an NSInteger. The following code is issuing warning:
Incompatible Pointer to Integer Conversion initializing NSInteger with an expression of type 'id'
NSInteger insertID = jsonResults[#"insert_id"];
I have tried various combinations of int, NSNumber, etc. to no avail. Can anyone suggest right way to do this?
NSDictionary can't store NSInteger. It is storing NSNumber. So you need to unwrap the NSNumber:
NSInteger insertID = [jsonResults[#"insert_id"] integerValue];
in core data you should save numeric value as Number Type.
For eaxample,
To save:
insert_id = #(100)//say 100 is your insert_id value
To read:
NSInteger insertID = [jsonResults[#"insert_id"] intValue];

Float array to float *

What is the difference between float[] and float*?
Also, how can I convert a float array to float *? I need to get a float * and open it, then apply a filter and send it as a float * into my FFT method, but I don't know how to do it because I don't know the real difference between them.
An array usually is a pointer to the first member of the list. When using Array[Identifier], you are accessing to *(p+Identifier).
Making a new array will define a series of pointer next to another, which will make it's use way easier.
You can set your float array in the following ways:
float array1[100] = { 0 };
float *dataArray = (float*)malloc(sizeof(float) * 100);
float *pointerToFloatArray = array1;
These points all relate to C:
the name of an array can be decomposed — i.e. implicitly converted — to a pointer to its first element;
in an array, elements are stored contiguously;
the syntax a[8] is just shorthand for *(a + 8); and
adding n to a pointer, p, is defined to add n * sizeof(*p).
So an array differs from a pointer by being a semantically different thing. But you can supply the name of an array anywhere a pointer is required as it'll be converted.
Separately, you can also add an offset to any pointer using subscript syntax.
Objective-C is a strict superset of C. So these rules also apply to the use of the primitive types in Objective-C.
To understand the distinction, think in terms of mutability. The following is invalid:
char array[];
char value;
array = &value;
You can't reassign array. It is the name of an array. array itself is not mutable at runtime, only the things within it are. Conversely the following is valid:
char *pointer;
char value;
pointer = &value;
You can reassign pointer as often as you like. There's a mutable pointer and you can use it to point to anything.
You can use C-style arrays, like described in this answer: https://stackoverflow.com/a/26263070/3399208,
but better way - is using Objective-C containers and Objective-C objects, for example NSNumber * :
NSArray *array = [#1, #2, #3];
or
NSMutableArray *array = [NSMutableArray array];
NSNumber *number1 = [NSNumber numberWithFloat:20.f];
NSNumber *number2 = #(20.f);
[array addObject:number1];
[array addObject:number2];

adding Char or NSString into Objective C enum

I have created an enum in my header file that looks like this
typedef enum {stTMD = 1, stT2MD = 2, stDCMD = 'D', stMBMD = 'M'} stTypes;
First off I am not even sure if thats the correct way to declare a char in an enum but
As you can see some values are integers and others are chars. However I am getting the following error when I try to place these values into a NSDicitonary like this
NSDictionary *iCTypes = [[NSDictionary alloc] initWithObjectsAndKeys:stDCMD,#"stMB", stMBMD,#"stMBMD", nil];
but I am getting this error below
Implicit conversion of 'int' to 'id' is disallowed with ARC
any help would be greatly appreciated.
An enum is basically an int type. Your enum definition is just fine. The problem is your use in the dictionary. You need to wrap the enum values in an NSNumber.
Try:
NSDictionary *iCTypes = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:stDCMD], #"stMB", [NSNumber numberWithInt:stMBMD] ,#"stMBMD", nil];
or even better (using modern Objective-C):
NSDictionary *icTypes = #{ #(stDCMD) : #"stMB", #(stMBMD) : #"stMBMD" };
You need to store objects inside it, so you can't store an int, rather a NSNumber, which can be made by appending a # before the number constant:
NSDictionary *iCTypes = [[NSDictionary alloc] initWithObjectsAndKeys: #(stDCMD),#"stMB", #(stMBMD),#"stMBMD", nil];
However a clarification is needed on this:
First off I am not even sure if thats the correct way to declare a char in an enum but As you can see some values are integers and others are chars.
When you define an enum it stores integers, it doesn't matter if you set chars as values, they're compatible with int so the compiler will not complain. But the storage type is the same, they're still integers and any type compatible with integers will be accepted.
Both the objects and keys in an NSDictionary must be objects, and the keys specifically must be objects that conform to NSCopying. In order to use ints in an NSDictionary, you have to convert them to NSNumbers. You can use either [NSNumber numberWithInt:stDCMD] or, if you're using a newer version of Xcode, #(stDCMD).
In C char is a kind of short int.
enum can only hold integer types.
NSDictionary cannot hold C types. Only objects.
You can wrap your C types in NSValue or NSNumber to put in an NSDictionary.

How do I use a core data Integer 64 property?

I want to have an Entity property in Core Data be a 64-bit integer. Since the model is going to run on iOS, and as far as I know these devices are not 64-bit, I figured that NSNumber was the way to go (core data gives you the option of objects or scalar properties for primitive types).
I'm assuming that NSNumber will internally take care of keeping track of a suitable representation for 64 bits.
Now, I need to subtract 1 from this "64 bit" property in my entity at some point (in case you didn't guess, the 64 bit property is the max_id parameter in the Twitter API), but to do so, I first need to unbox the number inside the NSNumber property.
So should i get the intValue? longValue? unsignedIntValue? unsignedLongValue? long long? which one?
Since you already know the type (64 bit integer), you don't need to check for it.
To get a 64 bit integer out of a NSNumber, do one of the following:
NSInteger myInteger = [myNSNumber integerValue];
int64_t myInteger = [myNSNumber integerValue];
In order to just add one to it, you can use something like this:
myNSNumber = [NSNumber numberWithInteger:[myNSNumber integerValue]+1]];
Note that iOS does have 64 bit data types like int64_t and NSInteger.
EDIT:
If the only reason that you are using NSNumber is to store the 64 bit integer, you can just declare the property like this in your model subclass and skip the unboxing/boxing altogether:
#property (nonatomic) int64_t myIntValue;
Note that core data does this by default if you select the Use scalar properties for primitive data types option of the Create NSManagedObject Subclass feature.
Try putting this in a NSNumber category:
-(int64_t) int64value
{
if (sizeof(short) == 8)
return [self shortValue];
if (sizeof(int) == 8)
return [self intValue];
if (sizeof(long) == 8)
return [self longValue];
if (sizeof(long long) == 8)
return [self longLongValue];
return -1; // or throw an exception
}
To get the C type contained in NSNumber use objCType
Example
NSNumber *myFloat = [NSNumber numberWithFloat:5.5f];
NSLog(#"%s", [myFloat objCType]);
Will print "f" as it contains a value of type float.
Also, check out #encode() which will return a C type character.
Example
NSNumber *myFloat = [NSNumber numberWithFloat:5.5f];
if (strcmp(myFloat) == #encode(float)) {
NSLog(#"This is a float");
}
Also
NSNumber *myFloat = [NSNumber numberWithFloat:5.5f];
CFNumberType numberType = CFNumberGetType((CFNumberRef)myFloat);

Resources