Search Results

Search found 6745 results on 270 pages for 'objective c'.

Page 14/270 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • object_getInstanceVariable works for float, int, bool, but not for double?

    - by Russel West
    I've got object_getInstanceVariable to work as here however it seems to only work for floats, bools and ints not doubles. I do suspect I'm doing something wrong but I've been going in circles with this. float myFloatValue; float someFloat = 2.123f; object_getInstanceVariable(self, "someFloat", (void*)&myFloatValue); works, and myFloatValue = 2.123 but when I try double myDoubleValue; double someDouble = 2.123f; object_getInstanceVariable(self, "someDouble", (void*)&myDoubleValue); i get myDoubleValue = 0. If I try to set myDoubleValue before the function eg. double myDoubleValue = 1.2f, the value is unchanged when I read it after the object_getInstanceVariable call. setting myIntValue to some other value before the getinstancevar function above returns 2 as it should, ie. it has been changed. then I tried Ivar tmpIvar = object_getInstanceVariable(self, "someDouble", (void*)&myDoubleValue); if i do ivar_getName(tmpIvar) i get "someDouble", but myDoubuleValue = 0 still! then i try ivar_getTypeEncoding(tmpIvar) and i get "d" as it should be. So to summarize, if typeEncoding = float, it works, if it is a double, the result is not set but it correctly reads the variable and the return value (Ivar) is also correct. I must be doing something basic wrong that I cant see so I'd appreciate if someone could point it out.

    Read the article

  • Mac OS X linker error in Qt; CoreGraphics & CGWindowListCreate

    - by Jake Petroules
    Here is my .mm file #include "windowmanagerutils.h" #ifdef Q_OS_MAC #import </System/Library/Frameworks/ApplicationServices.framework/Frameworks/CoreGraphics.framework/Headers/CGWindow.h> QRect WindowManagerUtils::getWindowRect(WId windowId) { CFArrayRef windows = CGWindowListCreate(kCGWindowListOptionOnScreenOnly, kCGNullWindowID); return QRect(); } QRect WindowManagerUtils::getClientRect(WId windowId) { return QRect(); } QString WindowManagerUtils::getWindowText(WId windowId) { return QString(); } WId WindowManagerUtils::rootWindow() { QApplication::desktop()->winId(); } WId WindowManagerUtils::windowFromPoint(const QPoint &p, WId parent, bool(*filterFunction)(WId)) { return NULL; } void WindowManagerUtils::setTopMostCarbon(const QWidget *const window, bool topMost) { if (!window) { return; } // Find a Cocoa equivalent for this Carbon function // [DllImport("/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")] // OSStatus ret = HIViewSetZOrder(this->winId(), kHIViewZOrderAbove, NULL); } #endif The linker is telling me "_CGWindowListCreate" is undefined. What libraries must I link to? Apple's documentation is not very helpful on telling what to include or link to, like MSDN is. Also I couldn't just do #import <CGWindow.h>, I had to specify the absolute path to it... any way around that?

    Read the article

  • Singleton Issues in iOS http client

    - by Andrew Lauer Barinov
    I implemented an HTTP client is iOS that is meant to be a singleton. It is a subclass of AFNetworking's excellent AFHTTPClient My access method is pretty standard: + (LBHTTPClient*) sharedHTTPClient { static dispatch_once_t once = 0; static LBHTTPClient *sharedHTTPClient = nil; dispatch_once(&once, ^{ sharedHTTPClient = [[LBHTTPClient alloc] initHTTPClient]; }); return sharedHTTPClient; } // my init method - (id) initHTTPClient { self = [super initWithBaseURL:[NSURL URLWithString:kBaseURL]]; if (self) { // Sub class specific initializations } return self; } Super's init method is very long, and can be found here However the problem I experience is when the dispatch_once queue is run, the app locks and become unresponsive. When I step through code, I notice that it locks on dispatch_once and then remains frozen. Is this something to do with the main thread locking down? How come it stays locked like that? Also, none of the HTTP client methods fire. Stepping through the code some more, I find this line in dispatch/once.h is where the app locks down: DISPATCH_INLINE DISPATCH_ALWAYS_INLINE DISPATCH_NONNULL_ALL DISPATCH_NOTHROW void _dispatch_once(dispatch_once_t *predicate, dispatch_block_t block) { if (DISPATCH_EXPECT(*predicate, ~0l) != ~0l) { dispatch_once(predicate, block); // App locks here } }

    Read the article

  • Dock tile plug-ins for not running applications

    - by kiamlaluno
    Is the dock tile plug-in of an application used even when the application is not active? The documentation says that the dock title plug-in is used when the application is loaded in the dock, but that means that the application is running of that the application is put in the dock because the user wants it to stay on the dock?

    Read the article

  • Objects not loading on second request in Restkit

    - by Holger Edward Wardlow Sindbæk
    I'm sending off 2 requests simultaneously with Restkit and I receive a response back from both of them, but only one of the requests receives any objects. If I send them off one by one, then my objectloader receives all objects. First request: self.firstObjectManager = [RKObjectManager sharedManager]; [self.firstObjectManager loadObjectsAtResourcePath:[NSString stringWithFormat: @"/%@.json", subUrl] usingBlock:^(RKObjectLoader *loader){ [loader.mappingProvider setObjectMapping:designArrayMapping forKeyPath:@""]; loader.userData = @"design"; loader.delegate = self; [loader sendAsynchronously]; }]; Second request: self.secondObjectManager = [RKObjectManager sharedManager]; [self.secondObjectManager loadObjectsAtResourcePath:[NSString stringWithFormat: @"/%@.json", subUrl] usingBlock:^(RKObjectLoader *loader){ [loader.mappingProvider setObjectMapping:designerMapping forKeyPath:@""]; loader.userData = @"designer"; loader.delegate = self; [loader sendAsynchronously]; }]; My objecloader: -(void)objectLoader:(RKObjectLoader *)objectLoader didLoadObjects:(NSArray *)objects { //NSLog(@"This happened: %@", objectLoader.userData); if (objectLoader.userData == @"design") { NSLog(@"Design happened: %i", objects.count); }else if(objectLoader.userData == @"designer"){ NSLog(@"designer: %@", [objects objectAtIndex:0]); } } My response: 2012-11-18 14:36:19.607 RestKitTest5[14220:c07] Started loading of request: designer 2012-11-18 14:36:22.575 RestKitTest5[14220:c07] I restkit.network:RKRequest.m:680:-[RKRequest updateInternalCacheDate] Updating cache date for request <RKObjectLoader: 0x95c3160> to 2012-11-18 19:36:22 +0000 2012-11-18 14:36:22.576 RestKitTest5[14220:c07] response code: 200 2012-11-18 14:36:22.584 RestKitTest5[14220:c07] Design happened: 0 2012-11-18 14:36:22.603 RestKitTest5[14220:c07] I restkit.network:RKRequest.m:680:-[RKRequest updateInternalCacheDate] Updating cache date for request <RKObjectLoader: 0xa589b50> to 2012-11-18 19:36:22 +0000 2012-11-18 14:36:22.605 RestKitTest5[14220:c07] response code: 200 2012-11-18 14:36:22.606 RestKitTest5[14220:c07] designer: <DesignerData: 0xa269fc0> Update: Setting my base url RKURL *baseURL = [RKURL URLWithBaseURLString:@"http://iphone.meer.li"]; [RKObjectManager setSharedManager:[RKObjectManager managerWithBaseURL:baseURL]]; Solution Problem was that I used the shared manager for both object managers, so I ended up doing: RKURL *baseURL = [RKURL URLWithBaseURLString:@"http://iphone.meer.li"]; RKObjectManager *myObjectManager = [[RKObjectManager alloc] initWithBaseURL:baseURL]; self.firstObjectManager = myObjectManager; and: RKURL *baseURL = [RKURL URLWithBaseURLString:@"http://iphone.meer.li"]; RKObjectManager *myObjectManager = [[RKObjectManager alloc] initWithBaseURL:baseURL]; self.secondObjectManager = myObjectManager;

    Read the article

  • Looking for marg_setValue in UIKit

    - by John Smith
    I am trying to compile a library originally written for Cocoa. Things are good until it looks for the function marg_setValue(). It says it can't find it. I have googled and found it is defined in How can I use this file in cocoa-touch? Or does cocoa-touch not support runtime.

    Read the article

  • Completion block not being called. How to check validity?

    - by HCHogan
    I have this method which takes a block, but that block isn't always called. See the method: - (void)updateWithCompletion:(void (^)(void))completion { [MYObject myMethodWithCompletion:^(NSArray *array, NSError *error) { if (error) { NSLog(@"%s, ERROR not nil", __FUNCTION__); completion(); return; } NSLog(@"%s, calling completion %d", __FUNCTION__, &completion); completion(); NSLog(@"%s, finished completion", __FUNCTION__); }]; } I have some more NSLogs inside completion. Sometimes this program counter just blows right past the call to completion() in the code above. I don't see why this would be as the calling code always passes a literal block of code as input. If you're curious of the output of the line containing the addressof operator, it's always something different, but never 0 or nil. What would cause completion not to be executed?

    Read the article

  • Looking for marg_setValue fix in iPhoneOS

    - by John Smith
    I am trying to compile a library originally written for Cocoa. Things are good until it looks for the function marg_setValue(). It says there is a syntax error before char in marg_setValue(argumentList,argumentOffset,char,(char)lua_toboolean(state,luaArgument)); (it's talking about the third argument, not (char) ) I am trying to port LuaObjectiveCBridge to the iPhone. It has two choices, either using Runtime or Foundation. I have discovered there are some problems with foundation so I am trying runtime. But the compiler is not co-operating.

    Read the article

  • Compare two Xcode build settings

    - by John Smith
    I have a project where I use two build settings predominantly. Unfortunately today something went wrong. One compiles and the other doesn't. How can I compare the two build settings in XCode to see what the differences are? (For those interested, the error I get in one build is jump to case label crosses initialization of 'const char* selectorName' if you know what this means I'll be very grateful )

    Read the article

  • Different results coming out of an init method than those expected. Why does this happen and how can

    - by Mark Reid
    When I run this method the two properties I have are set to (NULL) when I try and access them outside of the if statement. But they are set to 0 and NO if I check them inside the for loop. -(id) init { NSLog(@"Jumping into the init method!"); if (self = [super init]) { NSLog(@"Running the init method extras"); accumulator = 0; NSLog(@"self.accumulator is %g", accumulator); decimal = NO; } NSLog(@"Calc after init is: %@ and %@", self.accumulator, self.decimal); return self; } Any suggestions as to why what comes out is different from what's done in the for loop?

    Read the article

  • Returning from method inside a @synchronized block

    - by Michael Waterfall
    I'd just like to know if it's advised to return from a method within a @synchronized block? For example: - (id)test { @synchronized(self) { if (a) return @"A"; else return @"B"; } } As opposed to: - (id)test { NSString *value; @synchronized(self) { if (a) value = @"A"; else value = @"B"; } return value; } This sample is rather simplistic, but sometimes in a complex method it would make things simpler to be able to return from within a @synchronized block.

    Read the article

  • C As Principal Class For Mac App

    - by CodaFi
    So, I've got a c file raring to go and be the main class behind an all-C mac-app, however, a combination of limiting factors are preventing the application from being launched. As it currently stands, the project is just a main.m and a class called AppDelegate.c, so I entered "AppDelegate" as the name of the principal class in the info.plist, and to my complete surprise, the log printed: Unable to find class: AppDelegate, exiting This would work perfectly well in iOS, because the main function accepts the name of a delegate class, and handles it automatically, but NSApplicationMain() takes no such argument. Now, I know this stems from the fact that there are no @interface/@implementation directives in C, and that's really what the OS seems to be looking for, so I wrote a simple NSApplication subclass and provided it as the Principal Class to the plist, and it launched perfectly well. My question is, how could one go about setting a c file as the principal class in a mac application and have it launch correctly? PS, don't ask what or why I'm doing this for, the foundation must be dug. For @millimoose's amusement, here be the AppDelegate.c file: #include <objc/runtime.h> #include <objc/message.h> struct AppDel { Class isa; id window; }; // This is a strong reference to the class of the AppDelegate // (same as [AppDelegate class]) Class AppDelClass; BOOL AppDel_didFinishLaunching(struct AppDel *self, SEL _cmd, void *application, void *options) { self->window = objc_msgSend(objc_getClass("NSWindow"), sel_getUid("alloc")); self->window = objc_msgSend(self->window, sel_getUid("init")); objc_msgSend(self->window, sel_getUid("makeKeyAndOrderFront:"), self); return YES; }

    Read the article

  • Call instance method with objc_msgSend

    - by user772349
    I'm trying to use the objc_msgSend method to call some method dynamically. Say I want call some method in Class B from Class A and there are two methods in class B like: - (void) instanceTestWithStr1:(NSString *)str1 str2:(NSString *)str1; + (void) methodTestWithStr1:(NSString *)str1 str2:(NSString *)str1; And I can call the class method like this in Class A successfully: objc_msgSend(objc_getClass("ClassB"), sel_registerName("methodTestWithStr1:str2:"), @"111", @"222"); And I can call the instance method like this in Class A successfully as well: objc_msgSend([[objc_getClass("ClassB") alloc] init], sel_registerName("instanceTestWithStr1:str2:"), @"111", @"222"); But the thing is to get a instance of Class B I have to call "initWithXXXXX:XXXXXX:XXXXXX" instead of "init" so that to pass some necessary parameters to class B to do the init stuff. So I stored a instance of ClassB in class A as variable: self.classBInstance = [[ClassB alloc] initWithXXXXX:XXXXXX:XXXXXX]; And then I call the method like this (successfully): The problem is, I want to call a method by simply applying the classname and the method sel like "ClassName" and "SEL" and then call it dynamically: If it's a class method. then call it like: objc_msgSend(objc_getClass("ClassName"), sel_registerName("SEL")); If it's a instance method, find the existing class instance variable in the calling class then: objc_msgSend([self.classInstance, sel_registerName("SEL")); So I want to know if there is any way to: Check if a class has a given method (I found "responseToSelector" will be the one) Check if a given method in class method or instance method (maybe can use responseToSelector as well) Check if a class has a instance variable of a given class So I can call a instance method like: objc_msgSend(objc_getClassInstance(self, "ClassB"), sel_registerName("SEL"));

    Read the article

  • Add a hidden view above a UITableView that is only displayed when TableView is scrolled up

    - by noncogitas
    Goal/Situation: I currently have a UIView in the TableView header. I am trying to add another UIView (which contains two Buttons and a few TextFields) that will sit above the TableView header. I would like the view to be displayed when the user scrolls up past the header (a la "pull to refresh"), and go away when the user presses a "done" button on the view. My two questions: 1) How do I add a view above the tableview header? 2) How do I display said view when a user has scrolled up past the header? 3) How do I dismiss said view when the user has pressed a button on said view?

    Read the article

  • objective-c uncompress/inflate a NSData object which contains a gzipped string

    - by user141146
    Hi, I'm using objective-c (iPhone) to read a sqlite table that contains blob data. The blob data is actually a gzipped string. The blob data is read into memory as an NSData object I then use a method (gzipInflate) which I grabbed from here (http://www.cocoadev.com/index.pl?NSDataCategory) -- see method below. However, the gzipInflate method is returning nil. If I step through the gzipInflate method, I can see that the status returned near the bottom of the method is -3, which I assume is some type of error (Z_STREAM_END = 1 and Z_OK = 0, but I don't know precisely what a status of -3 is). Consequently, the function returns nil even though the input NSData is 841 bytes in length. Any thoughts on what I'm doing wrong? Is there something wrong with the method? Something wrong with how I'm using the method? Any thoughts on how to test this? Thanks for any help! - (NSData *)gzipInflate { // NSData *compressed_data = [self.description dataUsingEncoding: NSUTF16StringEncoding]; NSData *compressed_data = self.description; if ([compressed_data length] == 0) return compressed_data; unsigned full_length = [compressed_data length]; unsigned half_length = [compressed_data length] / 2; NSMutableData *decompressed = [NSMutableData dataWithLength: full_length + half_length]; BOOL done = NO; int status; z_stream strm; strm.next_in = (Bytef *)[compressed_data bytes]; strm.avail_in = [compressed_data length]; strm.total_out = 0; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; if (inflateInit2(&strm, (15+32)) != Z_OK) return nil; while (!done) { // Make sure we have enough room and reset the lengths. if (strm.total_out >= [decompressed length]) [decompressed increaseLengthBy: half_length]; strm.next_out = [decompressed mutableBytes] + strm.total_out; strm.avail_out = [decompressed length] - strm.total_out; // Inflate another chunk. status = inflate (&strm, Z_SYNC_FLUSH); NSLog(@"zstreamend = %d", Z_STREAM_END); if (status == Z_STREAM_END) done = YES; else if (status != Z_OK) break; //status here actually is -3 } if (inflateEnd (&strm) != Z_OK) return nil; // Set real length. if (done) { [decompressed setLength: strm.total_out]; return [NSData dataWithData: decompressed]; } else return nil; }

    Read the article

  • Integers not properly returned from a property list (plist) array in Objective-C

    - by Gaurav
    In summary, I am having a problem where I read what I expect to be an NSNumber from an NSArray contained in a property list and instead of getting a number such as '1', I get what looks to be a memory address (i.e. '61879840'). The numbers are clearly correct in the property list. Below is my process for creating the property list and reading it back. Creating the property list I have created a simple Objective-C property list with arrays of integers within one root array: <array> <array> <integer>1</integer> <integer>2</integer> </array> <array> <integer>1</integer> <integer>2</integer> <integer>5</integer> </array> ... more arrays with integers ... </array> The arrays are NSArray objects and the integers are NSNumber objects. The property list has been created and serialized using the following code: // factorArray is an NSArray that contains NSArrays of NSNumbers as described above // serialize and compress factorArray as a property list, Factors-bin.plist NSString *error; NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [rootPath stringByAppendingPathComponent:@"Factors-bin.plist"]; NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:factorArray format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]; Inspecting the created plist, all values and types are correct. Reading the property list The property list is read in as Data and then converted to an NSArray: NSString *path = [[NSBundle mainBundle] pathForResource:@"Factors" ofType:@"plist"]; NSData *plistData = [[NSData alloc] initWithContentsOfFile:path]; NSPropertyListFormat format; NSString *error = nil; NSArray *factorData = (NSArray *)[NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error]; Cycling through factorData to see what it contains is where I see the erroneous integers: for (int i = 0; i < 10; i++) { NSArray *factorList = (NSArray *)[factorData objectAtIndex:i]; NSLog(@"Factors of %d\n", i + 1); for (int j = 0; j < [factorList count]; j++) { NSLog(@" %d\n", (NSNumber *)[factorList objectAtIndex:j]); } } I see all the correct number of values, but the values themselves are incorrect, i.e.: Factors of 3 61879840 (should be 1) 61961200 (should be 3) Factors of 4 61879840 (should be 1) 61943472 (should be 2) 61943632 (should be 4) Factors of 5 61879840 (should be 1) 61943616 (should be 5)

    Read the article

  • Defining a Class in Objective C, XCode

    - by Brett
    Hello; I am new to Objective C, and am trying to write a class that defines a complex number. The code seems fine but when I print to the console, my values for instance variables are 0. Here is the code: // // ComplexNumber.h // Mandelbrot Set // // Created by Brett on 10-06-02. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> #import <stdio.h> @interface ComplexNumber : NSObject { double real; double imaginary; } // Getters -(double) real; -(double) imaginary; // Setters -(void)setReal: (double) a andImaginary: (double) b; //Function -(ComplexNumber *)squared; @end // // ComplexNumber.m // Mandelbrot Set // // Created by Brett on 10-06-02. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "ComplexNumber.h" #import <math.h> #import <stdio.h> @implementation ComplexNumber -(double)real{ return self->real; } -(double)imaginary{ return self->imaginary; } -(void)setReal: (double) a andImaginary: (double) b{ self->real=a; self->imaginary=b; } -(ComplexNumber *)squared{ double a = pow(real,2); double b = pow(imaginary, 2); double c = 2*real*imaginary; ComplexNumber *d; [d setReal:(a-b) andImaginary: c]; return d; } @end In the App Delegate for debugging purposes I added: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { ComplexNumber *testNumber = [[ComplexNumber alloc] init]; [testNumber setReal:55.0 andImaginary:30.0]; NSLog(@"%d", testNumber.real); // Override point for customization after app launch [window addSubview:viewController.view]; [window makeKeyAndVisible]; return YES; } But the console returns 0 everytime. Help?

    Read the article

  • Lua and Objective C not running script.

    - by beta
    I am trying to create an objective c interface that encapsulates the functionality of storing and running a lua script (compiled or not.) My code for the script interface is as follows: #import <Cocoa/Cocoa.h> #import "Types.h" #import "lua.h" #include "lualib.h" #include "lauxlib.h" @interface Script : NSObject<NSCoding> { @public s32 size; s8* data; BOOL done; } @property s32 size; @property s8* data; @property BOOL done; - (id) initWithScript: (u8*)data andSize:(s32)size; - (id) initFromFile: (const char*)file; - (void) runWithState: (lua_State*)state; - (void) encodeWithCoder: (NSCoder*)coder; - (id) initWithCoder: (NSCoder*)coder; @end #import "Script.h" @implementation Script @synthesize size; @synthesize data; @synthesize done; - (id) initWithScript: (s8*)d andSize:(s32)s { self = [super init]; self->size = s; self->data = d; return self; } - (id) initFromFile:(const char *)file { FILE* p; p = fopen(file, "rb"); if(p == NULL) return [super init]; fseek(p, 0, SEEK_END); s32 fs = ftell(p); rewind(p); u8* buffer = (u8*)malloc(fs); fread(buffer, 1, fs, p); fclose(p); return [self initWithScript:buffer andSize:size]; } - (void) runWithState: (lua_State*)state { if(luaL_loadbuffer(state, [self data], [self size], "Script") != 0) { NSLog(@"Error loading lua chunk."); return; } lua_pcall(state, 0, LUA_MULTRET, 0); } - (void) encodeWithCoder: (NSCoder*)coder { [coder encodeInt: size forKey: @"Script.size"]; [coder encodeBytes:data length:size forKey:@"Script.data"]; } - (id) initWithCoder: (NSCoder*)coder { self = [super init]; NSUInteger actualSize; size = [coder decodeIntForKey: @"Script.size"]; data = [[coder decodeBytesForKey:@"Script.data" returnedLength:&actualSize] retain]; return self; } @end Here is the main method: #import "Script.h" int main(int argc, char* argv[]) { Script* script = [[Script alloc] initFromFile:"./test.lua"]; lua_State* state = luaL_newstate(); luaL_openlibs(state); luaL_dostring(state, "print(_VERSION)"); [script runWithState:state]; luaL_dostring(state, "print(_VERSION)"); lua_close(state); } And the lua script is just: print("O Hai World!") Loading the file is correct, but I think it messes up at pcall. Any Help is greatly appreciated. Heading

    Read the article

  • My mental block - struggling to learn Objective C

    - by iqessar
    Hello people, this would be my first question after signing up! Anyway heres my question, I did Java at university and I was always told I am a good programmer. However I never pursued it as a career - I went into support and management instead. Im pretty much bored with my job, I have therefore started to learn Objective C so that I can develop apps for the iphone. I am currently watching several different Videos / Books. My problem is that when I go through the Apple documentation, although I understand most of it, sometimes I stumble. I believe that because you/we have the Apple documentation (i.e. Framework references) , everything should be clear, and therefore you should have no need to refer to a book or video (in order to learn how to use a particular class). But I alway do refer to a book and video and subsequently feel guilty as I believe the framework reference should be enough. (I therefore feel I am not up to being a programmer) I also believe that you shouldn't need example code in order to learn how to use a particular class because Apple provides documentation for each class, but AGAIN I find my self googling example code and I find my answer like that - again I feel guilty for doing this. Am I right in saying that Apple documentation is simply not clear? and that its ok to refer to a video/book or google? or forums for that matter? I have proffesional programmers who tell me that I am worrying too much and that I should get on with it and use all the resources that I have. I just cant seem to get round this mental block that I have in my head. When I start a programming project I am able to use the excellent search skills that I have to find the code I need, copy and paste it (yes I do understand it) BUT then I feel guilty telling myself that why didn't you think up the code yourself???? Therefore your not a real programmer, your just good at googling. Currently I am going through 20+ books so that I can learn most of the frameworks, syntax etc to develop iphone apps. I believe if I do this, then when I think of a project I can make it quickly. Should I read a few books, like 2-3 and then just start a project /app , and if I get stuck just google it and get the code I need? Can anybody please answer my questions?

    Read the article

  • Objective-c design advice for use of different data sources, swapping between test and live

    - by user200341
    I'm in the process of designing an application that is part of a larger piece of work, depending on other people to build an API that the app can make use of to retrieve data. While I was thinking about how to setup this project and design the architecture around it, something occurred to me, and I'm sure many people have been in similar situations. Since my work is depending on other people to complete their tasks, and a test server, this slows work down at my end. So the question is: What's the best practice for creating test repositories and classes, implementing them, and not having to depend on altering several places in the code to swap between the test classes and the actual repositories / proper api calls. Contemplate the following scenario: GetDataFromApiCommand *getDataCommand = [[GetDataFromApiCommand alloc]init]; getDataCommand.delegate = self; [getDataCommand getData]; Once the data is available via the API, "GetDataFromApiCommand" could use the actual API, but until then a set of mock data could be returned upon the call of [getDataCommand getData] There might be multiple instances of this, in various places in the code, so replacing all of them wherever they are, is a slow and painful process which inevitably leads to one or two being overlooked. In strongly typed languages we could use dependency injection and just alter one place. In objective-c a factory pattern could be implemented, but is that the best route to go for this? GetDataFromApiCommand *getDataCommand = [GetDataFromApiCommandFactory buildGetDataFromApiCommand]; getDataCommand.delegate = self; [getDataCommand getData]; What is the best practices to achieve this result? Since this would be most useful, even if you have the actual API available, to run tests, or work off-line, the ApiCommands would not necessarily have to be replaced permanently, but the option to select "Do I want to use TestApiCommand or ApiCommand". It is more interesting to have the option to switch between: All commands are test and All command use the live API, rather than selecting them one by one, however that would also be useful to do for testing one or two actual API commands, mixing them with test data. EDIT The way I have chosen to go with this is to use the factory pattern. I set up the factory as follows: @implementation ApiCommandFactory + (ApiCommand *)newApiCommand { // return [[ApiCommand alloc]init]; return [[ApiCommandMock alloc]init]; } @end And anywhere I want to use the ApiCommand class: GetDataFromApiCommand *getDataCommand = [ApiCommandFactory newApiCommand]; When the actual API call is required, the comments can be removed and the mock can be commented out. Using new in the message name implies that who ever uses the factory to get an object, is responsible for releasing it (since we want to avoid autorelease on the iPhone). If additional parameters are required, the factory needs to take these into consideration i.e: [ApiCommandFactory newSecondApiCommand:@"param1"]; This will work quite well with repositories as well.

    Read the article

  • Calculating negative fractions in Objective C

    - by Mark Reid
    I've been coding my way through Steve Kochan's Programming in Objective-C 2.0 book. I'm up to an exercise in chapter 7, ex 4, in case anyone has the book. The question posed by the exercise it will the Fraction class written work with negative fractions such as -1/2 + -2/3? Here's the implementation code in question - @implementation Fraction @synthesize numerator, denominator; -(void) print { NSLog(@"%i/%i", numerator, denominator); } -(void) setTo: (int) n over: (int) d { numerator = n; denominator = d; } -(double) convertToNum { if (denominator != 0) return (double) numerator / denominator; else return 1.0; } -(Fraction *) add: (Fraction *) f { // To add two fractions: // a/b + c/d = ((a * d) + (b * c)) / (b * d) // result will store the result of the addition Fraction *result = [[Fraction alloc] init]; int resultNum, resultDenom; resultNum = (numerator * f.denominator) + (denominator * f.numerator); resultDenom = denominator * f.denominator; [result setTo: resultNum over: resultDenom]; [result reduce]; return result; } -(Fraction *) subtract: (Fraction *) f { // To subtract two fractions: // a/b - c/d = ((a * d) - (b * c)) / (b * d) // result will store the result of the addition Fraction *result = [[Fraction alloc] init]; int resultNum, resultDenom; resultNum = numerator * f.denominator - denominator * f.numerator; resultDenom = denominator * f.denominator; [result setTo: resultNum over: resultDenom]; [result reduce]; return result; } -(Fraction *) multiply: (Fraction *) f { // To multiply two fractions // a/b * c/d = (a*c) / (b*d) // result will store the result of the addition Fraction *result = [[Fraction alloc] init]; int resultNum, resultDenom; resultNum = numerator * f.numerator; resultDenom = denominator * f.denominator; [result setTo: resultNum over: resultDenom]; [result reduce]; return result; } -(Fraction *) divide: (Fraction *) f { // To divide two fractions // a/b / c/d = (a*d) / (b*c) // result will store the result of the addition Fraction *result = [[Fraction alloc] init]; int resultNum, resultDenom; resultNum = numerator * f.denominator; resultDenom = denominator * f.numerator; [result setTo: resultNum over: resultDenom]; [result reduce]; return result; } -(void) reduce { int u = numerator; int v = denominator; int temp; while (v != 0) { temp = u % v; u = v; v = temp; } numerator /= u; denominator /= u; } @end My question to you is will it work with negative fractions and can you explain how you know? Part of the issue is I don't know how to calculate negative fractions myself so I'm not too sure how to know. Many thanks.

    Read the article

  • Objective-C vs JavaScript loop performance

    - by micadelli
    I have a PhoneGap mobile application that I need to generate an array of match combinations. In JavaScript side, the code hanged pretty soon when the array of which the combinations are generated from got a bit bigger. So, I thought I'll make a plugin to generate the combinations, passing the array of javascript objects to native side and loop it there. To my surprise the following codes executes in 150 ms (JavaScript) whereas in native side (Objective-C) it takes ~1000 ms. Does anyone know any tips for speeding up those executing times? When players exceeds 10, i.e. the length of the array of teams equals 252 it really gets slow. Those execution times mentioned above are for 10 players / 252 teams. Here's the JavaScript code: for (i = 0; i < GAME.teams.length; i += 1) { for (j = i + 1; j < GAME.teams.length; j += 1) { t1 = GAME.teams[i]; t2 = GAME.teams[j]; if ((t1.mask & t2.mask) === 0) { GAME.matches.push({ Team1: t1, Team2: t2 }); } } } ... and here's the native code: NSArray *teams = [[NSArray alloc] initWithArray: [options objectForKey:@"teams"]]; NSMutableArray *t = [[NSMutableArray alloc] init]; int mask_t1; int mask_t2; for (NSInteger i = 0; i < [teams count]; i++) { for (NSInteger j = i + 1; j < [teams count]; j++) { mask_t1 = [[[teams objectAtIndex:i] objectForKey:@"mask"] intValue]; mask_t2 = [[[teams objectAtIndex:j] objectForKey:@"mask"] intValue]; if ((mask_t1 & mask_t2) == 0) { [t insertObject:[teams objectAtIndex:i] atIndex:0]; [t insertObject:[teams objectAtIndex:j] atIndex:1]; /* NSArray *newCombination = [[NSArray alloc] initWithObjects: [teams objectAtIndex:i], [teams objectAtIndex:j], nil]; */ [combinations addObject:t]; } } } ... the array in question (GAME.teams) looks like this: { count = 2; full = 1; list = ( { index = 0; mask = 1; name = A; score = 0; }, { index = 1; mask = 2; name = B; score = 0; } ); mask = 3; name = A; }, { count = 2; full = 1; list = ( { index = 0; mask = 1; name = A; score = 0; }, { index = 2; mask = 4; name = C; score = 0; } ); mask = 5; name = A; },

    Read the article

  • changing output in objective-c app

    - by Zack
    // // RC4.m // Play5 // // Created by svp on 24.05.10. // Copyright 2010 __MyCompanyName__. All rights reserved. // #import "RC4.h" @implementation RC4 @synthesize txtLyrics; @synthesize sbox; @synthesize mykey; - (IBAction) clicked: (id) sender { NSData *asciidata1 = [@"4875" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *asciistr1 = [[NSString alloc] initWithData:asciidata1 encoding:NSASCIIStringEncoding]; //[txtLyrics setText:@"go"]; NSData *asciidata = [@"sdf883jsdf22" dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *asciistr = [[NSString alloc] initWithData:asciidata encoding:NSASCIIStringEncoding]; //RC4 * x = [RC4 alloc]; [txtLyrics setText:[self decrypt:asciistr1 andKey:asciistr]]; } - (NSMutableArray*) hexToChars: (NSString*) hex { NSMutableArray * arr = [[NSMutableArray alloc] init]; NSRange range; range.length = 2; for (int i = 0; i < [hex length]; i = i + 2) { range.location = 0; NSString * str = [[hex substringWithRange:range] uppercaseString]; unsigned int value; [[NSScanner scannerWithString:str] scanHexInt:&value]; [arr addObject:[[NSNumber alloc] initWithInt:(int)value]]; } return arr; } - (NSString*) charsToStr: (NSMutableArray*) chars { NSString * str = @""; for (int i = 0; i < [chars count]; i++) { str = [NSString stringWithFormat:@"%@%@",[NSString stringWithFormat:@"%c", [chars objectAtIndex:i]],str]; } return str; } //perfect except memory leaks - (NSMutableArray*) strToChars: (NSString*) str { NSData *asciidata = [str dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *asciistr = [[NSString alloc] initWithData:asciidata encoding:NSASCIIStringEncoding]; NSMutableArray * arr = [[NSMutableArray alloc] init]; for (int i = 0; i < [str length]; i++) { [arr addObject:[[NSNumber alloc] initWithInt:(int)[asciistr characterAtIndex:i]]]; } return arr; } - (void) initialize: (NSMutableArray*) pwd { sbox = [[NSMutableArray alloc] init]; mykey = [[NSMutableArray alloc] init]; int a = 0; int b; int c = [pwd count]; int d = 0; while (d < 256) { [mykey addObject:[pwd objectAtIndex:(d % c)]]; [sbox addObject:[[NSNumber alloc] initWithInt:d]]; d++; } d = 0; while (d < 256) { a = (a + [[sbox objectAtIndex:d] intValue] + [[mykey objectAtIndex:d] intValue]) % 256; b = [[sbox objectAtIndex:d] intValue]; [sbox replaceObjectAtIndex:d withObject:[sbox objectAtIndex:a]]; [sbox replaceObjectAtIndex:a withObject:[[NSNumber alloc] initWithInt:b]]; d++; } } - (NSMutableArray*) calculate: (NSMutableArray*) plaintxt andPsw: (NSMutableArray*) psw { [self initialize:psw]; int a = 0; int b = 0; NSMutableArray * c = [[NSMutableArray alloc] init]; int d; int e; int f; int g = 0; while (g < [plaintxt count]) { a = (a + 1) % 256; b = (b + [[sbox objectAtIndex:a] intValue]) % 256; e = [[sbox objectAtIndex:a] intValue]; [sbox replaceObjectAtIndex:a withObject:[sbox objectAtIndex:b]]; [sbox replaceObjectAtIndex:b withObject:[[NSNumber alloc] initWithInt:e]]; int h = ([[sbox objectAtIndex:a]intValue] + [[sbox objectAtIndex:b]intValue]) % 256; d = [[sbox objectAtIndex:h] intValue]; f = [[plaintxt objectAtIndex:g] intValue] ^ d; [c addObject:[[NSNumber alloc] initWithInt:f]]; g++; } return c; } - (NSString*) decrypt: (NSString*) src andKey: (NSString*) key { NSMutableArray * plaintxt = [self hexToChars:src]; NSMutableArray * psw = [self strToChars:key]; NSMutableArray * chars = [self calculate:plaintxt andPsw:psw]; NSData *asciidata = [[self charsToStr:chars] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; NSString *asciistr = [[NSString alloc] initWithData:asciidata encoding:NSUTF8StringEncoding]; return asciistr; } @end This is supposed to decrypt a hex string with an ascii string, using rc4 decryption. I'm converting my java application to objective-c. The output keeps changing, every time i run it.

    Read the article

  • Objective-C function dispatch collisions; Or, how to achieve "namespaces"?

    - by fbrereto
    I have an application for Mac OS X that supports plugins that are intended to be loaded at the same time. Some of these plugins are built on top of a Cocoa framework that may receive updates in one plugin but not another. Given Objective-C's current method for function dispatching, any call from any plugin to a given Objective-C routine will go to the same routine every time. That means plugin A can find itself inside plugin B with a trivial Objective-C call! Obviously what we're looking for is for each plugin to interact with its own version of the framework upon which it was built. I have been reading some on Objective-C and this particular need, but haven't found a definitive solution for it yet. Update: My use of the word "framework" above is misleading: the framework is a statically-linked library, built into the plugin(s) that need it. The way Objective-C handles dispatching, however, even these statically linked pieces of disparate code will co-mingle in the Objective-C dispatcher, leading to unintended consequences. Update 2: I'm still a bit fuzzy on the answer provided here, as it doesn't seem to propose a solution as much as an unproven hypothesis.

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >