Unused variable warning in objective c - objective-c

I'm trying to learn objective-c and have encountered a warning in this example:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
#autoreleasepool {
NSMutableDictionary *booklisting = [NSMutableDictionary dictionary];
int count; // < Am getting 'unused variable' warning here
[booklisting setObject:#"Wind in the Willows" forKey:#"100-432112"];
[booklisting setObject:#"Tale of Two Cities" forKey:#"200-532874"];
[booklisting setObject:#"Sense and Sensibility" forKey:#"200-546549"];
[booklisting setObject:#"Shutter Island" forKey:#"104-109834"];
NSLog(#"Number of books in dictionary = %lu", [booklisting count]);
would anyone know why?.. Would appreciate help..thanks

you are not using any where in your code.that's why warning comes like this.
int count;// count is an variable and
[booklisting count]//here count is a property of NSArray reference class
remove int count; and check it.

you arent using count... [booklisting count] is accessing a method of booklisting which is a NSMutableDictionary which has a method called count which returns how many entries are in the dictionary.
its coincidence that they have the same name.

put this line
count =[booklisting count];
before NSLog
or remove this int count; line
count is getter method for array.

Just remove int count; since you have not used variable count.

int count; // < Am getting 'unused variable' warning here
You declare a variable count.But it is never used.Hence the error is shown

Related

Sum two NSInteger gives incorrect result

Im haveing a problem suming two NSInteger, I have tried with simple int but cant find the answer. I Have this on my header file:
#interface ViewController : UIViewController {
NSMutableArray *welcomePhotos;
NSInteger *photoCount; // <- this is the number with the problem
//static int photoCount = 1;
}
The on my implementation fiel I have:
-(void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
photoCount = 0;
welcomePhotos = [NSMutableArray array];
int sum = photoCount + 1;
NSLog(#"0 + 1 = %i", sum);
}
The las NSLog always prints 0 + 1 = 4
Also if if do:
if (photoCount < [welcomePhotos count]){
photoCount++;
NSLog(#"%i", photoCount);
}else{
photoCount = 0;
}
Several times i get: 4, 8, 12.
So it is skiping by four, but I can't get to understand why.
You are declaring your photoCount instance var as pointer to NSInteger. But NSInteger is a scalar type.
Remove the asterisk in your .h file and try again.
Replace
NSInteger *photoCount;
with
NSInteger photoCount;
You're printing out a pointer object I believe as you've declared it as
NSInteger* photocount;
Try changing it to
int photocount;
doing a variable++ on an integer adds the size of a pointer which is 4 bytes on iOS.
You used pointer to NSInteger...
Change it to NSInteger photoCount;
NSInteger is just an int, and you are treating it as an wrapper object. Pointer in not required.

Convert variable name to string

How can I convert a variable name into a string?
Example:
From this:
NSString *someVariable
int otherVariable
I want to get a NSString with the actual name of the variable, no matter what type it is.
So, for the two variables above I would want to get their names (someVariable, otherVariable).
I managed to solve my problem with this code snippet:
Import the objc runtime
#import <objc/runtime.h>
and you can enumerate the properties with:
- (NSArray *)allProperties
{
unsigned count;
objc_property_t *properties = class_copyPropertyList([self class], &count);
NSMutableArray *rv = [NSMutableArray array];
unsigned i;
for (i = 0; i < count; i++)
{
objc_property_t property = properties[i];
NSString *name = [NSString stringWithUTF8String:property_getName(property)];
[rv addObject:name];
}
free(properties);
return rv;
}
Hope it helps someone.
Just add " ... " around the variable name. i.e.
"someVariable"
"otherVariable"
to get the string (as a const char*.) If you want an NSString*, use
#"someVariable"
#"otherVariable"
Within a macro, you can use the construction #... to put the quote ... unquote around a macro variable, e.g.
#define MyLog(var) NSLog(#"%s=%#", #var, var)
so that
MyLog(foo);
is expanded to
NSLog(#"%s=%#", "foo", foo);
These are C declarations, and C does not have the introspection capability to give you what you want.
You could probably write a preprocessor macro that would both declare a variable and also declare and initialize a second variable with the name of the first.
But this begs the question of why you need this level of introspection at all.

Unknown errors in Xcode

I am following the instructions for a tutorial but I cannot figure out what is wrong. I have double checked everything. I put the the compiler errors in the code's comments below. Sorry, this will probably show how much of a noob I am.
// main.m
#import <Foundation/Foundation.h>
#import "LotteryEntry.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// Creates the date object
NSCalendarDate *now = [[NSCalendarDate alloc]init];
//Seed the random number generator
srandom(time(NULL));
NSMutableArray * array;
array = [[NSMutableArray alloc]init];
int i;
for (i = 0; i < 10; i++) {
//create a date/time object that is 'i' weeks from now
NSCalendarDate *iWeeksFromNow;
iWeeksFromNow = [now dateByAddingYears:0
months:0
days:(i * 7)
hours:0
minutes:0
second:0];
}
//create the LotteryEntry object
LotteryEntry *newEntry = [[LotteryEntry alloc]init];
[newEntry prepareRandomNumbers];
[newEntry setEntryDate: iWeeksFromNow];
//Error says "Use of undeclared identifier "iWeeksFromNow'. Did I not declare it above?
//add the lottery entry object to the array
[array addObject:newEntry];
}
for (LotteryEntry *entryToPrint in array) {
//Error says " Expected identifier or '('
//Display it's contents
NSLog(#"%#", entryToPrint);
}
[pool drain];
return 0;
//Error says " Expected identifier or '('
}
//Error says " Expected External declaration
You are declaring iWeeksFromNow inside a for loop, that's why the compiler doesn't consider it to exist outside
declare it outside, and assign values to it inside
You have an extra closing } as you call the -dateByAddingYears method.
First error : you declare iWeeksFromNew inside a for loop, thus it's unreachable from outside.
You have to declare before the beginning of the loop.
Second error : you have a bracket '}' after [array addObject:newEntry]; so the compiler thinks its the end of your method, remove it.
That should fix all other error you have
First, iWeeksFromNow is declared within the scope of a for loop, so it will be visible only within that loop. Second, as pointed out by Black Frog, you have an extra closing parenthesis.
Move the declaration out that loop block. You've got a scope problem here: The iWeeksFromNew only exists within the loop
NSCalendarDate *iWeeksFromNow;
int i;
for (i = 0; i < 10; i++) {
//create a date/time object that is 'i' weeks from now
iWeeksFromNow = [now dateByAddingYears:0
months:0
days:(i * 7)
hours:0
minutes:0
second:0];
}

Passing NSArray to a cpp function

I need to call a cpp function like
void myFunc(float **array2D, int rows, int cols)
{
}
within an objective-c object. Basically, the array is created in my objective-c code as I create an NSArray object. Now, the problem is how to pass this array to my cpp function.
I am a bit new to these mixed c++/objective-c stuffs so any hint will be highly appreciated.
Thanks
I guess you have to convert the NSArray to a plain C array.
Something like:
NSArray *myNSArray; // your NSArray
int count = [myNSArray count];
float *array = new float[count];
for(int i=0; i<count; i++) {
array[i] = [[myNSArray objectAtIndex:i] floatValue];
}
or, as a commenter suggested (assuming your NSArray contains NSNumbers):
NSArray *myNSArray; // your NSArray
int count = [myNSArray count];
float *array = new float[count];
int i = 0;
for(NSNumber *number in myNSArray) {
array[i++] = [number floatValue];
}
Look at this post.
Check out the answer that mentions using [NSArray getObjects] to create a c-style array.
Here's the code that the poster put in there:
NSArray *someArray = /* .... */;
NSRange copyRange = NSMakeRange(0, [someArray count]);
id *cArray = malloc(sizeof(id *) * copyRange.length);
[someArray getObjects:cArray range:copyRange];
/* use cArray somewhere */
free(cArray);
Alternately, since CFArray is toll-free bridged to NSArray, could you call those C functions from your C++ function? I'd look around, wouldn't be surprised if there weren't a C++ wrapper to give similar semantics, or one could be written easily enough.

How do I list all fields of an object in Objective-C?

If I have a class, how can I list all its instance variable names?
eg:
#interface MyClass : NSObject {
int myInt;
NSString* myString;
NSMutableArray* myArray;
}
I would like to get "myInt", "myString", and "myArray". Is there some way to perhaps get an array of names that I can iterate over?
I've tried searching the Objective-C documentation but couldn't find anything (and I'm not sure what this is called either).
As mentioned, you can use the Objective-C runtime API to retrieve the instance variable names:
unsigned int varCount;
Ivar *vars = class_copyIvarList([MyClass class], &varCount);
for (int i = 0; i < varCount; i++) {
Ivar var = vars[i];
const char* name = ivar_getName(var);
const char* typeEncoding = ivar_getTypeEncoding(var);
// do what you wish with the name and type here
}
free(vars);
#import <objc/runtime.h>
NSUInteger count;
Ivar *vars = class_copyIvarList([self class], &count);
for (NSUInteger i=0; i<count; i++) {
Ivar var = vars[i];
NSLog(#"%s %s", ivar_getName(var), ivar_getTypeEncoding(var));
}
free(vars);
Consider gen_bridge_metadata, which is intended for a completely different purpose, but can produce XML files from Objective-C header files.