parse error on objective c - objective-c

#import <Foundation/NSArray.h>
#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSEnumerator.h>
#import <stdio.h>
void print( NSArray *array ) {
NSEnumerator *enumerator = [array objectEnumerator];
id obj;
while ( obj = [enumerator nextObject] ) {
printf( "%s\n", [[obj description] cString] );
}
}
int main( int argc, const char *argv[] ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *arr = [[NSArray alloc] initWithObjects:
#"Me", #"Myself", #"I", nil];
NSMutableArray *mutable = [[NSMutableArray alloc] init];
// enumerate over items
printf( "----static array\n" );
print( arr );
// add stuff
[mutable addObject: #"One"];
[mutable addObject: #"Two"];
[mutable addObjectsFromArray: arr];
[mutable addObject: #"Three"];
// print em
printf( "----mutable array\n" );
print( mutable );
// sort then print
printf( "----sorted mutable array\n" );
[mutable sortUsingSelector: #selector( caseInsensitiveCompare: )];
print( mutable );
// free memory
[arr release];
[mutable release];
[pool release];
return 0;
}
this program compiled with oscv0.1.4 in windows.
it gives an error as shown below
Error: Parse error on line 6:
...import <stdio.h>
void print( NSArray
---------------------^
Expecting 'INTERFACE', 'IMPLEMENTATION', 'PROTOCOL', 'IMPORT', 'CLASS', 'DEFINE', 'EOF'
now i got one more error for the program shown below(it is another program)
#import "Forwarder.h"
#import "Recipient.h"
int main(void)
{
Forwarder *forwarder = [Forwarder new];
Recipient *recipient = [Recipient new];
[forwarder setRecipient:recipient]; //Set the recipient.
[forwarder hello];
[recipient release];
[forwarder release];
return 0;
}
error is
Error: Parse error on line 3:
...Recipient : Object
- (id)hello;
#end#i
----------------------^
Expecting '<', '{'

the format of your program must like the code shown below
here main must contain Main class
compare this with the link
http://code.google.com/p/oscompiler/downloads/list
#interface Main : NSObject { }
#end
#implementation Main
+(void)main {
NSLog(#"Hello world!");
}
#end

Related

concatenate Strings from a NSArray?

#import <Foundation/Foundation.h>
#include <stdlib.h>
#include "GenerarPassword.h"
#implementation GenerarPassword
-(NSDictionary*) generarDiccionario
{
NSDictionary* m_Dict =[NSDictionary dictionaryWithObjectsAndKeys:
#"Dx", #"1",
#"Om", #"2",
#"Al", #"3",
#"Na", #"4",
#"Je", #"5",
#"Ko", #"6",
#"Ke", #"7",
#"Fi", #"8",
#"Re", #"9",
#"Me", #"10",
#"Mu", #"11",
#"Ra", #"12",
#"Lu", #"13",
#"Lo", #"14",
#"Ka", #"15"
,nil];
return m_Dict;
}
-(void) printPassword:(int) password
{
NSLog(#"%d",password);
}
/*Se genera la clave numérica*/
-(int) generarClave
{
srand(time(0));
int r = rand() %(9999-1000+1) +1000;
return r;
}
//Esta función Genera el valor Aleatorio
-(NSString*) GenerarValor:(NSString*) key
{
NSString *valor = [[self generarDiccionario] valueForKey: key];
return valor;
}
-(NSArray*) generarlistaletras:(int) numero
{
NSArray* lista = [[NSArray alloc] initWithObjects: [NSNumber numberWithInt:0], [NSNumber numberWithInt:0], [NSNumber numberWithInt:0],nil];
return lista;
}
-(void) imprimirArreglo:(NSArray*) arreglo
{
int i = 0;
NSString *str1 =#" ";
for (i=0;i<2;i++)
{
[str1 stringByAppendingString:[arreglo objectAtIndex:0]];
}
NSLog(#"%#",str1);
}
// lista = [0,0,0]
//lista[random.randrange(0,3)] = [GenerarValor(numero)]
//for i in range(len(lista)):
// if lista[i] == 0:
// lista[i] = [GenerarValor(random.randrange(11,20))]
// return lista
#end
int main(int argc, char const *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
GenerarPassword *Generar1 = [[GenerarPassword alloc]init];
int clave = [Generar1 generarClave];
[Generar1 printPassword:clave];
NSDictionary* dict = [Generar1 generarDiccionario];
NSLog(#"%#",[[Generar1 generarDiccionario] valueForKey:#"1"]);
[Generar1 imprimirArreglo:[Generar1 generarlistaletras:123]];
[pool drain];
return 0;
}
My idea is to print the array (the function imprimirArreglo), but when run the program I get this exception: Uncaught exception NSInvalidArgumentException, reason: Can not determine type information for -[NSIntNumber (null)]; what i wanted was to print the array with format 0 0 0.
OK, I edited your code into something more sensible.
#import <Foundation/Foundation.h>
#include "GenerarPassword.h"
#interface GenerarPassword ()
#property (nonatomic, strong) NSArray *generarArray;
#end
#implementation GenerarPassword
- (NSArray *)generarArray
{
if (!_generarArray) {
_generarArray = #[#"Dx", #"Om", #"Al", #"Na", #"Je", #"Ko", #"Ke", #"Fi", #"Re", #"Me", #"Mu", #"Ra", #"Lu", #"Lo", #"Ka"];
}
return _generarArray;
}
- (void)printPassword:(NSInteger)password
{
NSLog(#"%#", #(password));
}
/*Se genera la clave numérica*/
- (NSInteger)generarClave
{
return arc4random_uniform(9000) + 1000;
}
//Esta función Genera el valor Aleatorio
- (NSString *)generarValor:(NSInteger)key
{
return self.generarArray[key];
}
- (NSArray *)generarlistaletras:(NSInteger)numero
{
return #[#0, #0, #0];
}
- (void)imprimirArreglo:(NSArray *)arreglo
{
NSString *string1 = [NSString stringWithFormat:#"%#", [arreglo componentsJoinedByString:#" "]];
NSLog(#"%#", string1);
}
#end
int main(int argc, char const *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
GenerarPassword *generarPassword = [[GenerarPassword alloc] init];
NSInteger clave = [generarPassword generarClave];
[generarPassword printPassword:clave];
NSLog(#"%#", generarPassword.generarArray[0]);
[generarPassword imprimirArreglo:[generarPassword generarlistaletras:123]];
[pool drain];
return 0;
}
There are a few things I noticed.
First, if you're going to store value next to keys that are just counting numbers... then use an array not a dictionary.
Second, you're never actually calling the method generarValor so a lot of the code doesn't seem to be doing anything.
Third, you should really be using a property to store the array/dictionary in. You are repeatedly creating new dictionaries in your code.
The line NSDictionary* dict = [Generar1 generarDiccionario]; is actually just wasting processor cycles because you're not actually using dict at all.
Fourth, variable names and methods should start with a lowercase letter, class name start with an uppercase letter.
Fifth, there is a lot of useless code here. I think I've fixed the problem, in your imprimirArreglo method though.
Sixth, format your code nicely when you put it onto StackOverflow. Pretend you're doing and exam for college. No one here is paid so the chance they'll struggle through code that's all over the place is very small.
Also, take a look through the code. I've made some improvements and changes to it to make it Objective-C code and not C++ code.

fatal error on NSArray.h

I have ubuntu machine and compiling objective-c using GNUStep. I wrote the following code:
#import <objc/objc.h>
#import <Foundation/Foundation.h>
#import <objc/NSArray.h>
int main ( int argc, char ** argv)
{
int ar[100] = {0};
int i;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *arr = [[NSArray alloc] initWithObjects:#"stackOverflow", #"1", #"2", nil];
NSLog (# "Counts in the array %i", [arr count]);
#try {
NSString *str;
str = [arr objectAtIndex:1];
NSLog (#" String value is %# ", str);
}
#catch (NSRangeException * excep)
{
NSLog (#"Reached Range caught for %#:%#" [excep name], [excep reason]);
}
[pool release];
}
But I get the following fatal error:
fatal error: objc/NSArray.h: No such file or directory
I tried <NSArray.h> also, but getting same error.
Which path I have to provide?
The file objc/NSArray.h does not exist, hence the fatal error.
Remove the #import <objc/NSArray.h> as NSArray should already be available via the Foundation import.
See https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html

NSThread thread-safe implementation of initialize.?

The following code compiles and executes as expected.
#import <objc/objc.h>
#import <Foundation/Foundation.h>
BOOL loopValue = YES;
#interface myThread:NSObject
-(void) enterThread: (NSArray *) elemt count: (NSString *) x;
#end
#implementation myThread
-(void) enterThread : (NSArray *) elemt
{
NSLog (#" Inside mythread ");
NSAutoreleasePool *pool = [[ NSAutoreleasePool alloc] init];
int i;
int cnt =10;
for(i=0; i<cnt; i++) {
NSLog (#"Number of elemennts in array %i ", [elemt count]);
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
loopValue = NO;
[pool drain];
}
#end
int main ( int argc, char ** argv)
{
NSAutoreleasePool *pool = [[ NSAutoreleasePool alloc] init];
// id tobj = [[myThread alloc] init];
id tobj = [ myThread new ];
NSLog (#"Starting New Thread ");
[NSThread detachNewThreadSelector:#selector(enterThread:) toTarget:tobj withObject:[NSArray arrayWithObjects:#"ram",#"20",nil]];
while(1)
if ( loopValue )
[NSThread sleepUntilDate:[NSDate dateWithTimeIntervalSinceNow:2]];
else
break;
NSLog (#".. Exiting.. \n");
[pool drain];
return 0;
}
MY Question:
While compilation i do get the following warnings..
mythread.m:24:1: warning: incomplete implementation of class ‘myThread’ [enabled by default]
mythread.m:24:1: warning: method definition for ‘-enterThread:count:’ not found [enabled by default]
While Execution
WARNING your program is becoming multi-threaded, but you are using an ObjectiveC runtime library .... Removed due to redability]hich does not have a thread-safe implementation of the +initialize method. ......
What am i dong wrong ? how to avoid both warning/runtime errors.
The method you declared is enterThread:count: but the method you implement is enterThread:. Also, that warning you are getting, I'm sure I've only seen that from the old GNUstep runtime… but I guess not.

Can't access properties of returned objects?

//SomeObject.h
#import <Foundation/Foundation.h>
#interface SomeObject : NSObject {
}
#property NSInteger aProperty;
#end
//main.m
#import <Foundation/Foundation.h>
#import "SomeObject.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[[[SomeObject alloc] init] autorelease] forKey:#"key1"];
[dictionary setObject:[[[SomeObject alloc] init] autorelease] forKey:#"key2"];
[dictionary objectForKey:#"key1"].aProperty = 5; //Error HERE
[dictionary release];
[pool drain];
return 0;
}
But on that line XCode gives me these errors:
error: Semantic Issue: Member reference type 'struct objc_object *' is a pointer; maybe you meant to use '->'?
error: Semantic Issue: No member named 'aProperty' in 'struct objc_object'
Can't I access a property of a returned object? (I mean, without directly calling the setter method)
You need to cast the returned object:
((SomeObject*)[dictionary objectForKey:#"key1"]).aProperty = 5;
or:
[(SomeObject*)[dictionary objectForKey:#"key1"] setAProperty: 5];
or:
SomeObject* obj = [dictionary objectForKey:#"key1"];
obj.aProperty = 5;

What is the value of NSEnumerator?

when for . . . in . . . is available?
Specifically, when we can write:
NSArray *array;
// array allocated and initialized here.
for (id obj in array) {
// do something to the object here
}
Why would we ever use an NSEnumerator?
NSEnumerator was created before fast enumeration (for/in loop) was available. Think of it as backward-compatibility if you like.
But with NSEnumerator you can enumerate the collection in customized order, e.g. backwards:
NSEnumerator* enu = [array reverseObjectEnumerator];
id object;
while ((object = [enu nextObject])) {
...
}
(Of course, since NSEnumerator also supports for/in loop you can use a better way:
for (id object in [array reverseObjectEnumerator]) {
...
}
)
or define your own iterator class by subclassing NSEnumerator, e.g.
#import <Foundation/Foundation.h>
#interface RangeEnumerator : NSEnumerator {
int cur, len;
}
+(RangeEnumerator*)enumeratorWithLength:(int)length;
-(id)initWithLength:(int)length;
-(id)nextObject;
#end
#implementation RangeEnumerator
-(id)initWithLength:(int)length {
if ((self = [super init]))
len = length;
return self;
}
+(RangeEnumerator*)enumeratorWithLength:(int)length {
return [[(RangeEnumerator*)[self alloc] initWithLength:length] autorelease];
}
-(id)nextObject {
if (cur < len)
return [NSNumber numberWithInt:cur++];
else
return nil;
}
#end
int main () {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
for (NSNumber* num in [RangeEnumerator enumeratorWithLength:12])
printf("%d\n", [num intValue]);
[pool drain];
return 0;
}