Format for int since XCode 4.5 - ios

Since upgrading to XCode 4.5, printing ints to the console results in unusually high values. Eg:
int someInt = 300;
NSLog([NSString stringWithFormat:#"Some int: %d", someInt]); // prints Some int: 11581443
Usually I only see this when using the wrong format string for the data type. I'm using LLDB.

you wrong use NSLog.
void NSLog (
NSString *format,
...
);
ex:
int someInt = 100;
NSString* str = [NSString stringWithFormat:#"%d",someInt];
NSLog(#"%#",str);
or
NSLog(#"%d", someInt)
or
NSLog(#"%#", [NSString stringWithFormat:#"%d",someInt])

Try NSLog(#"Integer: %i", int)

#askovpen is right about your incorrect use of NSLog, however this line in your question is interesting :
using the wrong format string for the data type
Of course you get garbage out - you're putting garbage in!
NSLog works by using the first parameter to work out how big the other parameters are going to be. i.e. if you put %c it expects a char next in the parameters. If you put %d it expects an int. So if you pass in an int and tell it to expect a float then yea, it's not going to work. Why would you expect that it would?
The reason you might be getting different values in XCode 4.5 instead of other XCodes might be due to changes in the memory management during compilation, or might be due to any number of other things.

Related

Dynamically create NSString with Unicode emoji

I have the string #"Hi there! \U0001F603", which correctly shows the emoji like Hi there! 😃 if I put it in a UILabel.
But I want to create it dynamically like [NSString stringWithFormat:#"Hi there! \U0001F60%ld", (long)arc4random_uniform(10)], but it doesn't even compile.
If I double the backslash, it shows the Unicode value literally like Hi there! \U0001F605.
How can I achieve this?
A step back, for a second: that number that you have, 1F660316, is a Unicode code point, which, to try to put it as simply as possible, is the index of this emoji in the list of all Unicode items. That's not the same thing as the bytes that the computer actually handles, which are the "encoded value" (technically, the code units.
When you write the literal #"\U0001F603" in your code, the compiler does the encoding for you, writing the necessary bytes.* If you don't have the literal at compile time, you must do the encoding yourself. That is, you must transform the code point into a set of bytes that represent it. For example, in the UTF-16 encoding that NSString uses internally, your code point is represented by the bytes ff fe 3d d8 03 de.
You can't, at run time, modify that literal and end up with the correct bytes, because the compiler has already done its work and gone to bed.
(You can read in depth about this stuff and how it pertains to NSString in an article by Ole Begemann at objc.io.)
Fortunately, one of the available encodings, UTF-32, represents code points directly: the value of the bytes is the same as the code point's. In other words, if you assign your code point number to a 32-bit unsigned integer, you've got proper UTF-32-encoded data.
That leads us to the process you need:
// Encoded start point
uint32_t base_point_UTF32 = 0x1F600;
// Generate random point
uint32_t offset = arc4random_uniform(10);
uint32_t new_point = base_point_UTF32 + offset;
// Read the four bytes into NSString, interpreted as UTF-32LE.
// Intel machines and iOS on ARM are little endian; others byte swap/change
// encoding as necessary.
NSString * emoji = [[NSString alloc] initWithBytes:&new_point
length:4
encoding:NSUTF32LittleEndianStringEncoding];
(N.B. that this may not work as expected for an arbitrary code point; not all code points are valid.)
*Note, it does the same thing for "normal" strings like #"b", as well.
\U0001F603 is a literal which is evaluated at compile time. You want a solution which can be executed at runtime.
So you want to have a string with a dynamic unicode character. %C if the format specifier for a unicode character (unichar).
[NSString stringWithFormat:#"Hi there! %C", (unichar)(0x01F600 + arc4random_uniform(10))];
unichar is too small for emoji. Thanks #JoshCaswell for correcting me.
Update: a working answer
#JoshCaswell has the correct answer with -initWithBytes:length:encoding:, but I think I can write a better wrapper.
Create a function to do all the work.
Use network ordering for a standard byte order.
No magic number for the length.
Here is my answer
NSString *MyStringFromUnicodeCharacter(uint32_t character) {
uint32_t bytes = htonl(character); // Convert the character to a known ordering
return [[NSString alloc] initWithBytes:&bytes length:sizeof(uint32_t) encoding:NSUTF32StringEncoding];
}
So, in use…
NSString *emoji = MyStringFromUnicodeCharacter(0x01F600 + arc4random_uniform(10));
NSString *message = [NSString stringWithFormat:#"Hi there! %#", emoji];
Update 2
Finally, put in a category to make it real Objective-C.
#interface NSString (MyString)
+ (instancetype)stringWithUnicodeCharacter:(uint32_t)character;
#end
#implementation NSString (MyString)
+ (instancetype)stringWithUnicodeCharacter:(uint32_t)character {
uint32_t bytes = htonl(character); // Convert the character to a known ordering
return [[NSString alloc] initWithBytes:&bytes length:sizeof(uint32_t) encoding:NSUTF32StringEncoding];
}
#end
And again, in use…
NSString *emoji = [NSString stringWithUnicodeCharacter:0x01F600 + arc4random_uniform(10)];
NSString *message = [NSString stringWithFormat:#"Hi there! %#", emoji];

Objective C : Array

I am new to objective C and trying to learn it. I am trying to write calculator program which performs simple mathematical calculation(addition, subtraction and so forth).
I want to create an array which stores for numbers(double value) and operands. Now, my pushOperand method takes ID as below:
-(void) pushOperand:(id)operand
{
[self.inputStack addObject:operand];
}
when I try to push double value as below:
- (IBAction)enterPressed:(UIButton *)sender
{
[self.brain pushOperand:[self.displayResult.text doubleValue]];
}
It gives my following error: "Sending 'double' to parameter of incompatible type 'id'"
I would appreciate if you guys can answer my following questions:
'id' is a generic type so I would assume it will work with any type without giving error above. Can you please help me understand the real reason behind the error?
How can I resolve this error?
id is a pointer to any class. Hence, it does not work with primitive types such as double or int which are neither pointers, nor objects. To store a primitive type in an NSArray, one must first wrap the primitive in an NSNumber object. This can be done in using alloc/init or with the new style object creation, as shown in the two snippets below.
old style
NSNumber *number = [[NSNumber alloc] initWithDouble:[self.displayResult.text doubleValue]];
[self.brain pushOperand:number];
new style
NSNumber *number = #( [self.displayResult.text doubleValue] );
[self.brain pushOperand:number];
I suggest using it with an NSNumber: Try not to abuse using id where you don't need to; lots of issues can arise if not.
- (void)pushOperand:(NSNumber *)operand
{
[self.inputStack addObject:operand];
}
- (IBAction)enterPressed:(UIButton *)sender
{
[self.brain pushOperand:#([self.displayResult.text doubleValue])];
}

Displaying two different types of variables in one label string

I am trying to make a CCLabelTTF display a string and an integer together. Like this:
Your score is 0.
I've tried a few things but I usually get the warning Data argument not used by format string, and the label doesn't output the correct statements.
I am just trying to figure out the format in which to put these in and searching Google hasn't provided much, as I'm not really sure what exactly to search.
I've tried
label.string = (#"%#", #"hi", #"%d", investmentsPurchased);
but obviously that isn't correct. How would I do this?
Thanks.
(I assume this is ObjC and not Swift.) Try something like this:
label.string = [NSString stringWithFormat:#"hi %d", investmentsPurchased];
You use a single format string, which contains static text and replacement tokens (like %d) for any replacement variables. Then follows the list of values to substitute in. You can use multiple variables like:
label.string = [NSString stringWithFormat:#"number %d and a string %#", someInteger, someString];
use NSString newString = [NSString stringWithFormat:#"hello %#", investmentsPurchased];
in short: use stringWithFormat

NSArray.count returns incorrect, giant integer

I have the following code, intended to select a random string from the array.
NSArray *popupMessages = [NSArray arrayWithObjects:
#"Shoulda' been bobbin' and weaving! Need anything from the shop?",
#"Don't forget you can use old boss's guns! Available in the shop!",
#"Hey Chaz, you Bojo! You need more POWER! Come by the shop for some better weapons!",
#"Aw… lame. Maybe I got something that can help you out here at my shop!",
nil];
int pmCount = popupMessages.count; // Breakpoint Here - pmCount = 971056545
int messageIndex = arc4random() % pmCount; // Breakpoint Here - same as above
I am using ARC with cocos2d. Any ideas as to why the array's count returns such a huge number? Thanks!
Your problem just looks like it's a debugger artifact. It could be optimization-related, for example. Sometimes compilers can generate code that confuses debuggers pretty seriously. Add a log statement to make sure the debugger isn't just telling you lies.
"count" is not a property, AFAIK.
The way I usually get the count for an array is:
[popupMessages count];
Try:
NSInteger pmCount = [popupMessages count];

NSString to float...what happens if NSString is not numerical and contains alphanumeric characters?

if
NSString sample = #"1sa34hjh##";
Float 64 floatsample = [sample floatValue];
what happens? what does floatsample contain?
Read the documentation.
Return Value
The floating-point value of the receiver’s text as a float, skipping whitespace at the beginning of the string. Returns HUGE_VAL or –HUGE_VAL on overflow, 0.0 on underflow.
Also returns 0.0 if the receiver doesn’t begin with a valid text representation of a floating-point number.
The best way to figure out the return value is to check the return value yourself. You can create a small program and save it as a file with a .m extension. Here's a sample:
// floatTest.m
#import <Foundation/Foundation.h>
int main() {
NSString *sample = #"1sa34hjh##";
float floatsample = [sample floatValue];
printf("%f", floatsample);
return 0;
}
Compile it on the command-line using clang and linking with the Foundation framework.
clang floatTest.m -framework foundation -o floatTest
Then run the executable and see the output.
./floatTest
The printed value is 1.000000. So to answer your question, if the string starts with a number, then the number portion of the string will be taken and converted to float. Same rules as above apply on overflow or underflow.
If creating the files seems like a hassle, you might like this blog post on minimalist Cocoa programming.

Resources