Is it possible to suppress Xcode 4 static analyzer warnings? - objective-c

The Xcode 4 static analyzer reports in my code some false positives. Is there any way to suppress them?

I found a solution: false positives (like the Apple singleton design pattern) can be avoided with:
#ifndef __clang_analyzer__
// Code not to be analyzed
#endif
Analyzer will not analyze the code between those preprocessor directives.

Take a look at this page which shows how to use several #defines to annotate objective-c methods and parameters to help the static analyzer (clang) do the right thing
http://clang-analyzer.llvm.org/annotations.html
From that page:
The Clang frontend supports several source-level annotations in the
form of GCC-style attributes and pragmas that can help make using the
Clang Static Analyzer more useful. These annotations can both help
suppress false positives as well as enhance the analyzer's ability to
find bugs.

See my answer here. You can add a compile flag to the files and static analyzer will ignore them. This is probably better for 3rd party code you aren't concerned about, and not for first party code you are writing.

most of the time, using things like CF_RETURNS_RETAINED and following the 'create' rule works for me, but I ran into a case I could NOT suppress.
Finally found a way to suppress the analyzer by looking at llvm source code:
https://llvm.org/svn/llvm-project/cfe/trunk/test/ARCMT/objcmt-arc-cf-annotations.m.result
"Test to see if we suppress an error when we store the pointer to a
global."
static CGLayerRef sSuppressStaticAnalyzer;
static CGLayerRef sDmxImg[2][2][1000]; // a cache of quartz drawings.
CGLayerRef CachedDmxImg(...) // which lives for lifetime of app!
{
...
CGLayerRef img = sDmxImg[isDefault][leadingZeroes][dmxVal];
if ( !img )
{
NSRect imgRect = <some cool rectangle>;
[NSGraphicsContext saveGraphicsState];
CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
CGLayerRef cgLayerRef = CGLayerCreateWithContext(ctx, imgRect.size, NULL);
CGContextRef layerCtx = CGLayerGetContext(cgLayerRef);
[NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort:layerCtx flipped:YES]];
... draw some gorgeous expensive Quartz stuff ...
img = cgLayerRef;
sDmxImg[isDefault][leadingZeroes][dmxVal] = cgLayerRef;
sSuppressStaticAnalyzer = cgLayerRef; // suppress static analyzer warning!
[NSGraphicsContext restoreGraphicsState];
}
return img;
}
For some reason, assigning to a static array didn't suppress the warning, but assigning to a plain old static 'sSuppressStaticAnalyzer' does.
By the way the above method, using CGLayerRef is the fastest way I've found to redraw cached images (besides OpenGL).

Related

OpenGL with Cocoa: No matching function call when trying to call CGLLockContext([[self openGLContext] CGLContextObj]);

I am learning OpenGL. To get an OpenGL context setup I was following the GlEssentials example from Apple. The GlContext is there locked in the draw method as follows:
- (void) drawView
{
[[self openGLContext] makeCurrentContext];
// We draw on a secondary thread through the display link
// When resizing the view, -reshape is called automatically on the main
// thread. Add a mutex around to avoid the threads accessing the context
// simultaneously when resizing
CGLLockContext([[self openGLContext] CGLContextObj]);
[m_renderer render];
CGLFlushDrawable([[self openGLContext] CGLContextObj]);
CGLUnlockContext([[self openGLContext] CGLContextObj]);
}
When I tried to call CGLLockContext with exactly the same arguments as above in my view class I the following error:
No matching function for call to 'CGLLockContext
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.9.sdk/System/Library/Frameworks/OpenGL.framework/Headers/OpenGL.h:111:17: Candidate function not viable: cannot convert argument of incomplete type 'void *' to 'CGLContextObj' (aka '_CGLContextObject *')
Quickly inserting a typecast fixed the issue:
CGLLockContext((CGLContextObj)[[self openGLContext] CGLContextObj]);
Question is why? In Apples example it works fine without this typecast.
Two thoughts:
1) Are you doing this inside a C++ or ObjC++ file? That whole “candidate function” thing sounds like C++ to me, but I don’t really know C++.
2) Are your compiler flags (especially warnings and errors) the same in your project files as they are in Apple’s sample project. (I took a quick look at Xcode 5’s compiler settings and nothing jumped out at me.)

How to write iOS app purely in C

I read here Learn C Before Objective-C?
Usually I then replace some Obj-C code with pure C code (after all you can mix them as much as you like, the content of an Obj-C method can be entirely, pure C code)
Is this true?
Is it possible to build an iPhone app purely in the C programming language?
Damn, it took me a while but I got it:
main.c:
#include <CoreFoundation/CoreFoundation.h>
#include <objc/runtime.h>
#include <objc/message.h>
// This is a hack. Because we are writing in C, we cannot out and include
// <UIKit/UIKit.h>, as that uses Objective-C constructs.
// however, neither can we give the full function declaration, like this:
// int UIApplicationMain (int argc, char *argv[], NSString *principalClassName, NSString *delegateClassName);
// So, we rely on the fact that for both the i386 & ARM architectures,
// the registers for parameters passed in remain the same whether or not
// you are using VA_ARGS. This is actually the basis of the objective-c
// runtime (objc_msgSend), so we are probably fine here, this would be
// the last thing I would expect to break.
extern int UIApplicationMain(int, ...);
// Entry point of the application. If you don't know what this is by now,
// then you probably shouldn't be reading the rest of this post.
int main(int argc, char *argv[])
{
// Create an #autoreleasepool, using the old-stye API.
// Note that while NSAutoreleasePool IS deprecated, it still exists
// in the APIs for a reason, and we leverage that here. In a perfect
// world we wouldn't have to worry about this, but, remember, this is C.
id autoreleasePool = objc_msgSend(objc_msgSend(objc_getClass("NSAutoreleasePool"), sel_registerName("alloc")), sel_registerName("init"));
// Notice the use of CFSTR here. We cannot use an objective-c string
// literal #"someStr", as that would be using objective-c, obviously.
UIApplicationMain(argc, argv, nil, CFSTR("AppDelegate"));
objc_msgSend(autoreleasePool, sel_registerName("drain"));
}
AppDelegate.c:
#import <objc/runtime.h>
#import <objc/message.h>
// This is equivalent to creating a #class with one public variable named 'window'.
struct AppDel
{
Class isa;
id window;
};
// This is a strong reference to the class of the AppDelegate
// (same as [AppDelegate class])
Class AppDelClass;
// this is the entry point of the application, same as -application:didFinishLaunchingWithOptions:
// note the fact that we use `void *` for the 'application' and 'options' fields, as we need no reference to them for this to work. A generic id would suffice here as well.
BOOL AppDel_didFinishLaunching(struct AppDel *self, SEL _cmd, void *application, void *options)
{
// we +alloc and -initWithFrame: our window here, so that we can have it show on screen (eventually).
// this entire method is the objc-runtime based version of the standard View-Based application's launch code, so nothing here really should surprise you.
// one thing important to note, though is that we use `sel_getUid()` instead of #selector().
// this is because #selector is an objc language construct, and the application would not have been created in C if I used #selector.
self->window = objc_msgSend(objc_getClass("UIWindow"), sel_getUid("alloc"));
self->window = objc_msgSend(self->window, sel_getUid("initWithFrame:"), (struct CGRect) { 0, 0, 320, 480 });
// here, we are creating our view controller, and our view. note the use of objc_getClass, because we cannot reference UIViewController directly in C.
id viewController = objc_msgSend(objc_msgSend(objc_getClass("UIViewController"), sel_getUid("alloc")), sel_getUid("init"));
// creating our custom view class, there really isn't too much
// to say here other than we are hard-coding the screen's bounds,
// because returning a struct from a `objc_msgSend()` (via
// [[UIScreen mainScreen] bounds]) requires a different function call
// and is finicky at best.
id view = objc_msgSend(objc_msgSend(objc_getClass("View"), sel_getUid("alloc")), sel_getUid("initWithFrame:"), (struct CGRect) { 0, 0, 320, 480 });
// here we simply add the view to the view controller, and add the viewController to the window.
objc_msgSend(objc_msgSend(viewController, sel_getUid("view")), sel_getUid("addSubview:"), view);
objc_msgSend(self->window, sel_getUid("setRootViewController:"), viewController);
// finally, we display the window on-screen.
objc_msgSend(self->window, sel_getUid("makeKeyAndVisible"));
return YES;
}
// note the use of the gcc attribute extension (constructor).
// Basically, this lets us run arbitrary code before program startup,
// for more information read here: http://stackoverflow.com/questions/2053029
__attribute__((constructor))
static void initAppDel()
{
// This is objc-runtime gibberish at best. We are creating a class with the
// name "AppDelegate" that is a subclass of "UIResponder". Note we do not need
// to register for the UIApplicationDelegate protocol, that really is simply for
// Xcode's autocomplete, we just need to implement the method and we are golden.
AppDelClass = objc_allocateClassPair(objc_getClass("UIResponder"), "AppDelegate", 0);
// Here, we tell the objc runtime that we have a variable named "window" of type 'id'
class_addIvar(AppDelClass, "window", sizeof(id), 0, "#");
// We tell the objc-runtime that we have an implementation for the method
// -application:didFinishLaunchingWithOptions:, and link that to our custom
// function defined above. Notice the final parameter. This tells the runtime
// the types of arguments received by the function.
class_addMethod(AppDelClass, sel_getUid("application:didFinishLaunchingWithOptions:"), (IMP) AppDel_didFinishLaunching, "i#:##");
// Finally we tell the runtime that we have finished describing the class and
// we can let the rest of the application use it.
objc_registerClassPair(AppDelClass);
}
View.c
#include <objc/runtime.h>
// This is a strong reference to the class of our custom view,
// In case we need it in the future.
Class ViewClass;
// This is a simple -drawRect implementation for our class. We could have
// used a UILabel or something of that sort instead, but I felt that this
// stuck with the C-based mentality of the application.
void View_drawRect(id self, SEL _cmd, struct CGRect rect)
{
// We are simply getting the graphics context of the current view,
// so we can draw to it
CGContextRef context = UIGraphicsGetCurrentContext();
// Then we set it's fill color to white so that we clear the background.
// Note the cast to (CGFloat []). Otherwise, this would give a warning
// saying "invalid cast from type 'int' to 'CGFloat *', or
// 'extra elements in initializer'. Also note the assumption of RGBA.
// If this wasn't a demo application, I would strongly recommend against this,
// but for the most part you can be pretty sure that this is a safe move
// in an iOS application.
CGContextSetFillColor(context, (CGFloat []){ 1, 1, 1, 1 });
// here, we simply add and draw the rect to the screen
CGContextAddRect(context, (struct CGRect) { 0, 0, 320, 480 });
CGContextFillPath(context);
// and we now set the drawing color to red, then add another rectangle
// and draw to the screen
CGContextSetFillColor(context, (CGFloat []) { 1, 0, 0, 1 });
CGContextAddRect(context, (struct CGRect) { 10, 10, 20, 20 });
CGContextFillPath(context);
}
// Once again we use the (constructor) attribute. generally speaking,
// having many of these is a very bad idea, but in a small application
// like this, it really shouldn't be that big of an issue.
__attribute__((constructor))
static void initView()
{
// Once again, just like the app delegate, we tell the runtime to
// create a new class, this time a subclass of 'UIView' and named 'View'.
ViewClass = objc_allocateClassPair(objc_getClass("UIView"), "View", 0);
// and again, we tell the runtime to add a function called -drawRect:
// to our custom view. Note that there is an error in the type-specification
// of this method, as I do not know the #encode sequence of 'CGRect' off
// of the top of my head. As a result, there is a chance that the rect
// parameter of the method may not get passed properly.
class_addMethod(ViewClass, sel_getUid("drawRect:"), (IMP) View_drawRect, "v#:");
// And again, we tell the runtime that this class is now valid to be used.
// At this point, the application should run and display the screenshot shown below.
objc_registerClassPair(ViewClass);
}
It's ugly, but it works.
If you would like to download this, you can get it from my dropbox here
You can get it from my GitHub repository here:
Objective-C is a superset of the C-language, so it is theoretically possible to write a program entirely in C, however, unless you are thoroughly versed in OpenGL ES, You'll need to do at least some objC (Even Rich's sample has a const NSString* in it), else you'll have to write the views yourself.
OK, the above is completely wrong. Let me say, I'm astounded Rich achieved this lofty goal, so I ported it over to the mac (source here). The files below have no headers, do not link to Cocoa, nor does the project have a nib:
AppDelegate.m
#include <objc/runtime.h>
#include <objc/message.h>
extern id NSApp;
struct AppDel
{
Class isa;
//Will be an NSWindow later, for now, it's id, because we cannot use pointers to ObjC classes
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, id notification) {
//alloc NSWindow
self->window = objc_msgSend(objc_getClass("NSWindow"),
sel_getUid("alloc"));
//init NSWindow
//Adjust frame. Window would be about 50*50 px without this
//specify window type. We want a resizeable window that we can close.
//use retained backing because this thing is small anyhow
//return no because this is the main window, and should be shown immediately
self->window = objc_msgSend(self->window,
sel_getUid("initWithContentRect:styleMask:backing:defer:"),(NSRect){0,0,1024,460}, (NSTitledWindowMask|NSClosableWindowMask|NSResizableWindowMask|NSMiniaturizableWindowMask),NSBackingStoreRetained,NO);
//send alloc and init to our view class. Love the nested objc_msgSends!
id view = objc_msgSend(objc_msgSend(objc_getClass("View"), sel_getUid("alloc")), sel_getUid("initWithFrame:"), (struct CGRect) { 0, 0, 320, 480 });
// here we simply add the view to the window.
objc_msgSend(self->window, sel_getUid("setContentView:"), view);
objc_msgSend(self->window, sel_getUid("becomeFirstResponder"));
//makeKeyOrderFront: NSWindow to show in bottom left corner of the screen
objc_msgSend(self->window,
sel_getUid("makeKeyAndOrderFront:"),
self);
return YES;
}
static void initAppDel()
{
//Our appDelegate should be NSObject, but if you want to go the hard route, make this a class pair of NSApplication and try initing those awful delegate methods!
AppDelClass = objc_allocateClassPair((Class)
objc_getClass("NSObject"), "AppDelegate", 0);
//Change the implementation of applicationDidFinishLaunching: so we don't have to use ObjC when this is called by the system.
class_addMethod(AppDelClass,
sel_getUid("applicationDidFinishLaunching:"),
(IMP) AppDel_didFinishLaunching, "i#:#");
objc_registerClassPair(AppDelClass);
}
void init_app(void)
{
objc_msgSend(
objc_getClass("NSApplication"),
sel_getUid("sharedApplication"));
if (NSApp == NULL)
{
fprintf(stderr,"Failed to initialized NSApplication... terminating...\n");
return;
}
id appDelObj = objc_msgSend(
objc_getClass("AppDelegate"),
sel_getUid("alloc"));
appDelObj = objc_msgSend(appDelObj, sel_getUid("init"));
objc_msgSend(NSApp, sel_getUid("setDelegate:"), appDelObj);
objc_msgSend(NSApp, sel_getUid("run"));
}
//there doesn't need to be a main.m because of this little beauty here.
int main(int argc, char** argv)
{
//Initialize a valid app delegate object just like [NSApplication sharedApplication];
initAppDel();
//Initialize the run loop, just like [NSApp run]; this function NEVER returns until the app closes successfully.
init_app();
//We should close acceptably.
return EXIT_SUCCESS;
}
View.m
#include <objc/runtime.h>
#include <objc/message.h>
#include <ApplicationServices/ApplicationServices.h>
// This is a strong reference to the class of our custom view,
// In case we need it in the future.
Class ViewClass;
// This is a simple -drawRect implementation for our class. We could have
// used a UILabel or something of that sort instead, but I felt that this
// stuck with the C-based mentality of the application.
void View_drawRect(id self, SEL _cmd, CGRect rect)
{
//make a red NSColor object with its convenience method
id red = objc_msgSend(objc_getClass("NSColor"), sel_getUid("redColor"));
// fill target rect with red, because this is it!
NSRect rect1 = NSMakeRect ( 21,21,210,210 );
objc_msgSend(red, sel_getUid("set"));
NSRectFill ( rect1 );
}
// Once again we use the (constructor) attribute. generally speaking,
// having many of these is a very bad idea, but in a small application
// like this, it really shouldn't be that big of an issue.
__attribute__((constructor))
static void initView()
{
// Once again, just like the app delegate, we tell the runtime to
// create a new class, this time a subclass of 'UIView' and named 'View'.
ViewClass = objc_allocateClassPair((Class) objc_getClass("NSView"), "View", 0);
// and again, we tell the runtime to add a function called -drawRect:
// to our custom view. Note that there is an error in the type-specification
// of this method, as I do not know the #encode sequence of 'CGRect' off
// of the top of my head. As a result, there is a chance that the rect
// parameter of the method may not get passed properly.
class_addMethod(ViewClass, sel_getUid("drawRect:"), (IMP) View_drawRect, "v#:");
// And again, we tell the runtime that this class is now valid to be used.
// At this point, the application should run and display the screenshot shown below.
objc_registerClassPair(ViewClass);
}
prefix.pch
//
// Prefix header for all source files of the 'CBasedMacApp' target in the 'CBasedMacApp' project
//
#ifdef __OBJC__
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
#endif
I read here Learn C Before Objective-C?
Usually I then replace some Obj-C code with pure C code (after all you can mix them as much as you like, the content of an Obj-C method can be entirely, pure C code)
Is this true?
Could I build an iPhone app purely in the C programming language?
The quoted passage is true, but the answer to your question is no.
To illustrate what answerer Mecki on that other question was talking about:
- (void) drawRect:(CGRect)dirtyRect { //Objective-C
CGContextRef context = UIGraphicsGetCurrentContext(); //C
CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0); //C
CGContextFillRect(context, dirtyRect); //C
} //Objective-C (balances above “- (void) drawRect:…” line)
There is nothing but pure C code within this method, but the method itself is Objective-C code, as is the class that contains this method.
So it is possible to do what Mecki said, but you can't (practically—as Richard J. Ross III showed, it's technically possible but quite a lot of typing) write a whole Cocoa Touch program in pure C.
Actually, some of the code posted here, while written in C, is still calling objective-C code :). I don't know if that actually fits the scenario from the original poster when he asked
Is it possible to build an iPhone app purely in the C programming
language?
but I would agree with the people saying that, generally speaking and for an app with a GUI, you would need to write your GUI in OpenGL (which is C).
I think that is what most games do, right? Although I'm not sure if there's access to the iPhone's I/O (the touchscreen for example) in C.
Last but not least, the guys that wrote the code above rock! :)

Using #define to create styles

I am wondering if I can use a series of #DEFINE to create style options for my app.
For example,
#DEFINE style1: backGroundColor = [UIColor: colorNamed whiteColor];
txtColor = [UIColor blackColor]; #DEFINE style2....
My question is: What is the syntax for this statement?
While it is certainly possible to use DEFINE statements to create style options for your app, I'm wondering if the use of preprocessor directives makes sense for functionality such as styles, which are going to be collections to properties. If you use DEFINE statements to define your styles, it makes it difficult to ultimately provide style selection as a run-time option to your users.
Instead, I tend to think you will be better off creating a class hierarchy for this, and implementing it as a singleton. With a class hierarchy, you can define any general style behaviors in your root class, and then inherit from that to implement specific styles. Later on, you can expose the ability to select styles to your user if you want.
#define backgroundColor [UIColor whiteColor] then to use it you would say UIColor *txtColor = backgroundColor;.
Although you may only be able to use whiteColor as the definition instead of [UIColor whiteColor]. You would then call [UIColor backgroundColor]; instead of the above example.
I would not do this to generate stylings. Defining various settings outside of code would be a good idea but using defines is pretty binding and defeats the purpose of de-coupling the UI from code.
In a #define do not put a semicolon anywhere. When the preprocessor inserts the definition it will insert whatever semicolon is there exactly as it is; you do not want the preprocessor inserting semicolons. When writing the definition you probably don't know all the places you'll write it, therefore you shouldn't have a semicolon in it because you may write it inline an expression.
Another option is to use const instead.
In code I've written I have #defines for string literals #"literal string" and numbers. In other places I use the const declaration which looks like this:
//static type *const variableName = assignment;
static NSString *const kConstantString = #"Constant variable";
Constants don't use the preprocessor to fill in the information. If you access a define frequently and it uses some computation it might may be better suited to a constant declaration which is stored only once.
The other big reason I used const instead of #define is that define is not type-checked as it's handled by the preprocessor. Define basically turns off the compiler warnings and only gives you errors; strict warnings are extremely helpful and can save a lot of frustration.
Maybe you are looking for this syntax:
Setting a style
#define STYLE1
//#define STYLE2
and then anywhere in your code (class level or method level, header or implementation file).
#ifdef STYLE1
//code for the first style
UIColor* backgroundColor = [UIColor redColor];
#elif STYLE2
//code for the second style
UIColor* backgroundColor = [UIColor greenColor];
#else
//code for the third style
UIColor* backgroundColor = [UIColor clearColor];
#endif
More about C preprocessor: http://en.wikipedia.org/wiki/C_preprocessor

CADisplayLink and static variable magic in Apple OpenGl ES Sample

I would like an explanation of why XCode's OpenGl ES Sample works, please. It does the following to start the drawFrame method (in the blablaViewController.m - name is dependent on the project's name):
//sets up a CADisplayLink to do a regular (draw & update) call like this
CADisplayLink *aDisplayLink = [[UIScreen mainScreen] displayLinkWithTarget:self
selector:#selector(drawFrame)];
[aDisplayLink setFrameInterval:animationFrameInterval];
[aDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
and inside the drawFrame method it does the following:
//start of method
...
static float transY = 0.0f;
...
//Quite a lot of OpenGl code, I am showing only parts of the OpenGL ES1 version:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, (GLfloat)(sinf(transY)/2.0f), 0.0f);
transY += 0.075f;
...
//end of method
I don't know a lot of Objective C yet, but the way this transY variable is reset, then incremented in the same method is very weird. Since the GL_MODELVIEW matrix is reset to identity before being shifted, I don't think it could keep an accumulated value in opengl somewhere.
Is the static keyword the trick here? Does Objective C ignore all future variable declarations once something has been declared static once?
Thanks for the help!
Static variables get initializated at compile time in the binary, so only once, and for that reason you're forbidden to assign dynamic values for their initialization. Here, the variable transY is not set to 0.0 at every method call, but just on startup. That's why subsequent calls of the method can retrieve the old value.

Is there somethone wrong with my Object Scope?

This is a program I'm writing (myself as opposed to copying someone else's and thus not learning) as part of the ObjectiveC and Cocoa learning curve. I want to draw simple shapes on a NSView (limiting it to ovals and rectangles for now). The idea is that I record each NSBezierPath to an NSMutableArray so I can also investigate/implement saving/loading, undo/redo. I have a canvas, can draw on it as well as 2 buttons that I use to select the tool. To handle the path I created another object that can hold a NSBezierPath, color values and size value for each object drawn. This is what I want to store in the array. I use mouseDown/Dragged/Up to get coordinates for the drawing path. However, this is where things go wonky. I can instantiate the object that is supposed to hold the path/color/etc. info but, when I try to change an instance variable, the app crashes with no useful message in the debugger. I'll try to keep my code snippets short but tell me if I need to include more. The code has also degenerated a little from me trying so many things to make it work.
Project: Cocoa document based app
I have the following .m/.h files
MyDocument:NSDocument - generated by XCode
DrawnObject:NSObject - deals with the drawn object i.e. path, color, type (oval/rect) and size
Canvas:NSView - well, shows the drawing, deals with the mouse and buttons
Canvas is also responsible for maintaining a NSMutableArray of DrawnObject objects.
DrawnObject.h looks like this:
#import <Foundation/Foundation.h>
//The drawn object must know what tool it was created with etc as this needs to be used for generating the drawing
#interface DrawnObject : NSObject {
NSBezierPath * aPath;
NSNumber * toolType;//0 for oval, 1 for rectangular etc....
float toolSize;
struct myCol{
float rd;
float grn;
float blu;
float alp;
} toolColor;
}
-(void)setAPath:(NSBezierPath *) path;
-(NSBezierPath *)aPath;
#property (readwrite,assign) NSNumber * toolType;
-(float)toolSize;
-(void)setToolSize:(float) size;
-(struct myCol *)toolColor;
-(void)setCurrentColor:(float)ref:(float)green:(float)blue:(float)alpha;
#end
Canvas.h looks like this
#import
#import "drawnObject.h"
#interface Canvas : NSView {
NSMutableArray * myDrawing;
NSPoint downPoint;
NSPoint currentPoint;
NSBezierPath * viewPath;//to show the path as the user drags the mouse
NSNumber * currentToolType;
BOOL mouseUpFlag;//trying a diff way to make it work
BOOL mouseDrag;
}
-(IBAction)useOval:(id)sender;
-(IBAction)useRect:(id)sender;
-(IBAction)showTool:(id)sender;
-(NSRect)currentRect;
-(NSBezierPath *)createPath:(NSRect) aRect;
-(void)setCurrentToolType:(NSNumber *) t;
-(NSNumber *)currentToolType;
#end
In the Canvas.m file there are several functions to deal with the mouse and NSView/XCode also dropped in -(id)initWithFrame:(NSRect)frame and -(void)drawRect:(NSRect)rect Originally I use mouseUp to try to insert the new DrawnObject into the array but that caused a crash. So, now I use two BOOL flags to see when the mouse was released (clunky but I'm trying....)in drawRect to insert into the array. I've included the method below and indicated where it causes the app to fail:
- (void)drawRect:(NSRect)rect { //This is called automatically
// Drawing code here.
//NSLog(#"Within drawRect tool type is %d", [self currentTool]);
NSRect bounds = [self bounds];
NSRect aRect = [self currentRect];
viewPath = [self createPath:aRect];
//the createPath method uses the tool type to switch between oval and rect bezier curves
if(mouseUpFlag==YES && mouseDrag==YES){
mouseDrag=NO;
//Create a new drawnObject here
DrawnObject * anObject = [[DrawnObject alloc]init];//- WORKS FINE UP TO HERE
NSLog(#"CREATED NEW drawnObject");
[anObject setAPath:viewPath]; //- INSTANT APP DEATH!!!!
NSLog(#"Set a path in drawnObject");
[anObject setToolType:[[NSNumber alloc]initWithInt:5]];
NSLog(#"Set toolType in DrawnObject");
[anObject setToolType:currentToolType];
[myDrawing addObject:anObject];
NSLog(#"Added Object");
}
[[NSColor colorWithCalibratedRed:0.0 green:0.9 blue:0.0 alpha:0.5]set];
[NSBezierPath fillRect:bounds];
[[NSColor lightGrayColor]set];
[viewPath stroke]; //This is so the user can see where the drawing is being done
//Now, draw the paths in the array
[[NSColor blueColor]set];
for(DrawnObject * indexedObject in myDrawing){
[[indexedObject aPath] stroke];//This will do the actual drawing of ALL objects
}
}
I guess this has something to do with object scope or something but I just can not figure it out. As I said, as I've tried things the code has sort of undergone an metamorphosis, sadly not for the better. Like those BOOLS etc.
HELP! Any clever people out there, point me in the right direction please!
ADDED THIS ON:
-(NSBezierPath *)createPath:(NSRect) aRect
{
NSBezierPath * tempPath;
//I need to know what tool
switch(0){ //temporary - this would use the toolType as a selector
case 0:
tempPath = [NSBezierPath bezierPathWithOvalInRect:aRect];
break;
case 1:
tempPath = [NSBezierPath bezierPathWithRect:aRect];
break;
default:
tempPath = [NSBezierPath bezierPathWithOvalInRect:aRect];
break;
}
return tempPath;
}
You said your init method was:
-(void)init {
[super init];
//set default color = black
toolColor.rd=1.0;
toolColor.grn=1.0;
toolColor.blu=1.0;
toolColor.alp=1.0;
//set default size
toolSize=0.8;
//set default toolType
toolType=0;
//oval
NSLog(#"Init %#",self);
}
This is definitely wrong; read up on how to create an init method in the Obj-C guide or by reading sample code. Here's what it should look like:
-(id)init {
if (self = [super init]) {
//set default color = black
toolColor.rd=1.0;
toolColor.grn=1.0;
toolColor.blu=1.0;
toolColor.alp=1.0;
//set default size
toolSize=0.8;
//set default toolType
toolType=0;
//oval
NSLog(#"Init %#",self);
}
return self;
}
By not returning anything from -init, you were preventing the object's creation. Good luck! :-)
Edit: Ashley beat me to it...
What do you mean by “crash”?
Does anything appear in the Debugger Console (⇧⌘R)?
Does a stack trace appear in the Debugger window?
If there's a stack trace, where in your code does it crash?
It just hangs. In the debugger I see:
[Session started at 2008-11-28 14:40:34 +1000.]
2008-11-28 14:40:36.157 CH18Challenge_try2[1893:10b] Mouse Down at (80.000000,285.000000)
2008-11-28 14:40:36.333 CH18Challenge_try2[1893:10b] Mouse Up at (166.000000,217.000000)
2008-11-28 14:40:36.348 CH18Challenge_try2[1893:10b] Init
2008-11-28 14:40:36.349 CH18Challenge_try2[1893:10b] CREATED NEW drawnObject
[Session started at 2008-11-28 14:40:36 +1000.]
Loading program into debugger…
GNU gdb 6.3.50-20050815 (Apple version gdb-962) (Sat Jul 26 08:14:40 UTC 2008)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "i386-apple-darwin".Program loaded.
sharedlibrary apply-load-rules all
Attaching to program: `/Users/johan_kritzinger/Documents/Cocoa/CH18Challenge_try2/build/Debug/CH18Challenge_try2.app/Contents/MacOS/CH18Challenge_try2', process 1893.
(gdb)
Then I have to force quit to stop it.
We need to see the implementation of setAPath from DrawnObject.m. Also, for the "stack trace" look on the upper left of the debugger--it should list a stack of functions showing where in your code the crash is. Make sure you're running in Debug mode, not Release.
On the command line you can type print-object and you can
set a breakpoint in that line and step through it from there. It seems setAPath is somehow broken
Regards
Friedrich
What you have is not a crash. A crash is when a signal is raised (like EXC_BAD_ACCESS) or an uncaught exception.
What you have seems to be an infinite loop.
You need to use the pause button in the Debugger and see exactly where. I would guess that you have an infinite loop in your setAPath: method. You need to work out why this function is looping indefinitely.