Forum Navigation
You need to log in to create posts and topics.

fbcocoa Digest 4 Sep 2011 04:24:54 -0000 Issue 52

Posted by: carnationsoftware <carnationsoftware@...>

Steve,

Thanks for the Objective-C sample code.
It's really cool that you can do that from within FB
I have converted all of my windows and menus to NIBS
But I have not tried using any Objective-C code from within FB.
I have been using "Make Xcode Project" and then using Xcode to make any changes in Objective-C after the fact.
But it makes sense to be able to incorporate the code into the FB project
Rich

On Sep 3, 2011, at 11:24 PM, [email protected] wrote:


fbcocoa Digest 4 Sep 2011 04:24:54 -0000 Issue 52

Topics (messages 296 through 305)

Re: Tutorial_1
296 by: Bernie
298 by: Robert Purves
299 by: Brian S
300 by: Brian Stevens
301 by: Brian S
302 by: SVanVoorst

Tutorial_2
297 by: SVanVoorst

Tutorial_3
303 by: SVanVoorst

Tutorial_4
304 by: SVanVoorst

Re: [FB] FBCocoaTutorial
305 by: Brian S

Administrivia:

To subscribe to the digest, e-mail:
<[email protected]>

To unsubscribe from the digest, e-mail:
<[email protected]>

To post to the list, e-mail:
<[email protected]>

----------------------------------------------------------------------

From: Bernie <[email protected]>
Subject: Re: [fbcocoa] Tutorial_1
Date: September 1, 2011 6:44:16 PM CDT

Steve Van Voorst wrote:


This demo creates a basic window to which we can start adding controls.  To create demos/applications in obj-c, we need 3 files: .h, .m, and main.  FB takes care of the details for us automatically if we follow this template:

Thank Steve.
btw, for those new to this stuff, FBtoC Prefs/"Compile as Objective-C" must be checked, or (new in FB 5.6.1) add this line: compile as "Objective-C"
Bernie


To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: Robert Purves <[email protected]>
Subject: Re: [fbcocoa] Tutorial_1
Date: September 1, 2011 7:29:56 PM CDT

SVanVoorst wrote:

BeginCDeclaration

//@interface

//@end // interface

EndC

BeginCFunction

//@implementation

//@end //implementation

EndC

BeginCCode

...

EndC

Explanatory comments added to the template would make it self-documenting.

Robert P.

BeginCDeclaration // declarations for *.h
//@interface
//@end // interface
EndC

BeginCFunction // definitions for *.m
//@implementation
//@end // implementation
EndC

BeginCCode // main()
...
EndC

From: Brian S <[email protected]>
Subject: Re: [fbcocoa] Tutorial_1
Date: September 1, 2011 8:36:07 PM CDT
Good stuff Steve. Thank you.

Are you planning to explain any of the things that look mysterious to an FBer? Those who have already dabbled in Objective-C can just read the code( me, Bernie, you, Ken etc. )  but others might be a little lost. For example( and I’m playing devil’s advocate here ), what does:

 return NSApplicationMain(argc,  (const char **) argv);

do and why is it necessary?

Similarly, tutorial #2 introduces two new concepts ( controller and delegate ) without any description of them. I like the idea of starting slow and building on the prior tutorial but some kind of explanation/reference or something will be necessary. Maybe describe the skill level/knowledge required to understand the tutorial(s) and what prerequisite materials should be read/studied.

On Sep 1, 2011, at 3:16 PM, SVanVoorst wrote:


This demo creates a basic window to which we can start adding controls.  To create demos/applications in obj-c, we need 3 files: .h, .m, and main.  FB takes care of the details for us automatically if we follow this template:

'----- begin -----
BeginCDeclaration
//@end // interface
EndC
BeginCFunction
//@end //implementation
EndC
BeginCCode
{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
 
  [NSApplication sharedApplication];
  [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
    id menubar = [[NSMenu new] autorelease];
    id appMenuItem = [[NSMenuItem new] autorelease];
    [menubar addItem:appMenuItem];
    [NSApp setMainMenu:menubar];
    id appMenu = [[NSMenu new] autorelease];
    id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Quit"
        action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
    [appMenu addItem:quitMenuItem];
    [appMenuItem setSubmenu:appMenu];
   #define _wndW  430
   #define _wndH  300
    id window = [ [ NSWindow alloc ] 
                       initWithContentRect:NSMakeRect( 0, 0, _wndW, _wndH )
                       styleMask: NSClosableWindowMask | NSTitledWindowMask
                       backing:NSBackingStoreBuffered
                       defer:NO];
    [window center];
    [window setTitle: @"NSWindow" ];
    [window makeKeyAndOrderFront:nil]; 
  [NSApp activateIgnoringOtherApps:YES];
  [NSApp run];
  [pool drain];
  return NSApplicationMain(argc,  (const char **) argv);
}
EndC
'----- end -----
BeginCDeclaration...EndC becomes the .h file.  BeginCFunction...EndC becomes the .m file combined with main, which is created from BeginCCode...EndC.  Succeeding tutorials will build on this template; it will be used repetitively.
Sources of information: 1) XCode Documentation  2) Apple PDF files  3) Google  4) Books  5) Hopefully this List in the future
Steve Van Voorst


=


To unsubscribe, e-mail: [email protected] For additional commands,= e-mail: fbcocoa-help@freegro= ups.net

Brian S



To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: Brian Stevens <[email protected]>
Subject: Re: [fbcocoa] Tutorial_1
Date: September 1, 2011 8:45:45 PM CDT

On Sep 1, 2011, at 6:36 PM, Brian S wrote:


Similarly, tutorial #2 introduces two new concepts ( controller and delegate ) without any description of them. 

A partial answer might be to point the reader toward something that describes the MVC concept.

( <digression> - MVC in my old life was an IBM assembler move character instruction and I start thinking Op code, hex and base/displacement address </digression)

The controller needs to be described as an intermediary between the data( model ) and UI ( view ) but also is an object. Any description needs to further answer why it is needed( or desirable )
I’m willing to contribute but I don’t want to impose. I have time Sunday/Monday to write but I’m busy Fri/Sat.
Hope this gives you some ideas.

Brian S



To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: Brian S <[email protected]>
Subject: Fwd: [fbcocoa] Tutorial_1
Date: September 1, 2011 9:15:07 PM CDT
Sent from the wrong email 1st time, so it might have bounced. Sorry for the second send.

On Sep 1, 2011, at 6:36 PM, Brian S wrote:


Similarly, tutorial #2 introduces two new concepts ( controller and delegate ) without any description of them. 

A partial answer might be to point the reader toward something that describes the MVC concept.

( <digression> - MVC in my old life was an IBM assembler move character instruction and I start thinking Op code, hex and base/displacement address </digression)

The controller needs to be described as an intermediary between the data( model ) and UI ( view ) but also is an object. Any description needs to further answer why it is needed( or desirable )
I’m willing to contribute but I don’t want to impose. I have time Sunday/Monday to write but I’m busy Fri/Sat.
Hope this gives you some ideas.

Brian S



To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: SVanVoorst <[email protected]>
Subject: Re: [fbcocoa] Tutorial_1
Date: September 1, 2011 10:27:40 PM CDT

1)  <<what does: return NSApplicationMain(argc,  (const char **) argv); do and why is it necessary? >>

According to Chisnall, "Cocoa Programming Developer's Handbook", p. 140 it is equivalent to:

void  NSApplicationMain(int argc, char *argv[])
{
   [NSApplication sharedApplication];
   [NSBundle loadNibNamed: @"myMain" owner: NSApp];
   [NSApp run];
}
Since we are not using a nib, it seems to me we don't need line 2.  Lines 1 and 3 are already contained in the demo.  Therefore, we apparently do not need this line of code.  I have deleted it and the tested demos still run ok.  It will need more testing, but it sure looks like it can be safely omitted.  Thank you for pointing that out.
2) MVC stands for Model-View-Controller and is used extensively in Cocoa.  It is a design pattern which goes back to a language called Smalltalk.  You can briefly read more at en.wikipedia.org/wiki/Model–view–controllerA Controller works similar to installing a handler in Carbon Events.  It provides instruction for controls so that they will do whatever it is they are supposed to do.

3) A Delegate is a controller object that responds to a set of messages defined by the view.

4) I will move on to the next Tutorial after the discussion on this one is complete.  There are tons of information written about obj-c and the theory behind it.  There are lots of ways to learn.  My goal in presenting these tutorials is to give the programmer a template that he/she can use today and start to learn obj-c using our old friend, FB.  Furthermore, it can be used to create 64 bit, legacy free applications with the correct compiler settings.

Steve Van Voorst


To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: SVanVoorst <[email protected]>
Subject: Tutorial_2
Date: September 1, 2011 7:26:19 PM CDT

This demo starts to add controls to the window and demonstrates a controller and delegate.  Three ways to quit the application are shown: quit menu, quit button, and window close button.  These are basic closure methods and would be more complex if we needed to check for changes which had been made by the user.

'---- start -----
BeginCDeclaration
@interface AppDelegate : NSObject
//methods automatically called
@end //interface
EndC
BeginCFunction
@implementation AppDelegate
// --- Taken from NSApplicationDelegate Protocol Reference ---- //
-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *) theApp;
{
   return YES;
}
@end //implementation
EndC
BeginCDeclaration
@interface AppController : NSObject
{
}
// ---- Methods listed here ---- //
- (void) myBtnAction:(id)sender;
@end //interface
EndC
BeginCFunction
@implementation AppController
// --- Methods defined here ---- //
-(void) myBtnAction:(id)sender
{
  NSBeep();
}
@end //implementation
EndC
BeginCCode
{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
 
  [NSApplication sharedApplication];
  [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// --- Menu bar and menus ---- //
   id menubar = [[NSMenu new] autorelease];
   id appMenuItem = [[NSMenuItem new] autorelease];
   [menubar addItem:appMenuItem];
   [NSApp setMainMenu:menubar];
   id appMenu = [[NSMenu new] autorelease];
   id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Quit"
        action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
   [appMenu addItem:quitMenuItem];
   [appMenuItem setSubmenu:appMenu];
// ---- Window ------- //
   #define _wndW  430
   #define _wndH  300
   id window = [ [ NSWindow alloc ] 
                    initWithContentRect:NSMakeRect( 0, 0, _wndW, _wndH )
                    styleMask: NSClosableWindowMask | NSTitledWindowMask
                    backing:NSBackingStoreBuffered
                    defer:NO];
   [window center];
   [window setTitle: @"Controller/Delegate_demo" ];
   [window makeKeyAndOrderFront:nil]; 
// Create an instance of AppDelegate (NSObject)
  id myDelegate = [[AppDelegate alloc]init];
  [NSApp setDelegate:myDelegate];
// Create an instance of AppController (NSObject)
  id myController = [[AppController alloc]init];
  NSButton*btn = [[NSButton alloc]initWithFrame:NSMakeRect( 100, _wndH - 100, 150, 30 )];
  [[window contentView] addSubview: btn];
  [btn setBezelStyle:NSRoundedBezelStyle ];
  [btn setTitle: @"Beep" ];
  [btn setTarget:myController];
  [btn setAction:@selector(myBtnAction:)];
  [btn release];
  NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 130, 30, 95, 30 )];
  [quitBtn setBezelStyle:NSRoundedBezelStyle ];
  [quitBtn setTitle: @"Quit" ];
  [quitBtn setAction:@selector(terminate:)];
  [[window contentView] addSubview: quitBtn];
  [quitBtn release];
  [NSApp activateIgnoringOtherApps:YES];
  [NSApp run];
  [pool drain];
  return NSApplicationMain(argc,  (const char **) argv);
}
EndC
'------ end -----
Steve Van Voorst


To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: SVanVoorst <[email protected]>
Subject: Tutorial_3
Date: September 2, 2011 4:16:09 PM CDT

Now that we are able to open and close a window, we are going to need some controls (views) to fill it up.  Part of the following has been previously published, but new controls have been added.  Some controls work right out of the box; others will need to be hooked up later. Note that the NSStepper (little arrow) is connected to the display field without using a controller by using reciprocating Target/Action.  It may also be used with a controller.   If you want to see an image in the NSImageView, select one of your own .png images and put it in the folder with this demo.  You will have to name it "myImage.png" or else change the name in the demo (two places).  Un-REM the "include resources xxxx.png" line.  Please note the many bezel styles for NSButton.  Also note that the "grid" that they are printed in is unbalanced, ie it is not rectangular.  There supposedly is more overhead with this arrangement than with NSMatrix, but the latter only does rectangular configurations and so far I have not found a way to construct it by column; it prefers construction by row.  The main point that I would like to make is that many controls may be created using this common template.  Once the control has been created, it must then be added as a subview of the window's contentView and may then be released.

'----- start -----
/*
  Template code:
  NSWhatever *ctrlName = [[NSWhatever alloc] initWithFrame:NSMakeRect( left, top, width, height )];
  [[window contentView] addSubview:ctrlName];
  S.Van Voorst    {20110901}
*/
//include resources "myImage.png"
BeginCCode
{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
 
  [NSApplication sharedApplication];
  [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// ****** Menubar ****** //
    id menubar = [[NSMenu new] autorelease];
    id appMenuItem = [[NSMenuItem new] autorelease];
    [menubar addItem:appMenuItem];
    [NSApp setMainMenu:menubar];
    id appMenu = [[NSMenu new] autorelease];
    id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Quit"
        action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
    [appMenu addItem:quitMenuItem];
    [appMenuItem setSubmenu:appMenu];
// ****** Window ******* //
   #define _wndW  650
   #define _wndH  530
    id window = [ [ NSWindow alloc ] initWithContentRect:NSMakeRect( 0, 0, _wndW, _wndH )
                       styleMask: NSClosableWindowMask | NSTitledWindowMask
                       backing:NSBackingStoreBuffered
                       defer:NO];
    [window center];
    [window setTitle: @"Cocoa Controls - Programmatic" ];
    [window makeKeyAndOrderFront:nil]; 
// ***** Text Field ***** //
NSTextField *txtFld = [[NSTextField alloc] initWithFrame:NSMakeRect( 30, _wndH - 40, 240, 20 )];
[[window contentView] addSubview:txtFld];
[txtFld setStringValue:@"Welcome to Cocoa without a nib."];
[txtFld release];
// ***** Slider ****** //
NSSlider *slider = [[NSSlider alloc] initWithFrame:NSMakeRect( 30, _wndH - 72, 240, 20 )];
[[window contentView] addSubview:slider];
[slider setMinValue:0];
[slider setMaxValue:12];
[slider setIntValue:8];
[slider release];
// ****** ComboBox ****** //
NSComboBox *combo = [[NSComboBox alloc] initWithFrame:NSMakeRect( 30, _wndH - 102, 100, 24 )];
[[window contentView] addSubview:combo];
NSArray *fruit = [NSArray arrayWithObjects: @"Apples", @"Oranges", @"Peaches",nil];
[combo addItemsWithObjectValues:fruit];
[combo release];
// ***** PopUp with Menu ****** //
NSPopUpButton *pup = [[NSPopUpButton alloc] initWithFrame:NSMakeRect( 150, _wndH - 102, 120, 24 )];
[[window contentView] addSubview:pup];
[pup insertItemWithTitle:@"Item 1" atIndex:0];
[pup insertItemWithTitle:@"Item 2" atIndex:1];
[pup insertItemWithTitle:@"Item 3" atIndex:2];
[pup release];
// ****** ImageView ****** //
 NSImageView *imageView = [[NSImageView alloc] initWithFrame:NSMakeRect( 290, _wndH - 110, 100, 100 )]; 
 [[window contentView] addSubview:imageView];
 NSImage *image = [NSImage imageNamed:@"myImage.png"];
 [imageView setImageScaling:NSScaleToFit];
 [imageView setImage:image]; 
 [imageView release];
// ****** NSTextView with Scroll ****** //
NSScrollView *scrlView = [[NSScrollView alloc] initWithFrame:NSMakeRect( 410, _wndH - 140, 180, 120 )];
[[window contentView] addSubview:scrlView];
[scrlView setHasVerticalScroller: YES];
NSTextView *txtView = [[NSTextView alloc] initWithFrame:NSMakeRect( 250, _wndH - 260, 136, 100 )];
[scrlView setDocumentView: txtView];
[txtView insertText:@"Enter text - Right click for menu."];
[scrlView release];
[txtView release];
// ****** ColorWell ****** //
NSColorWell *well = [[NSColorWell alloc] initWithFrame:NSMakeRect( 30, _wndH - 150, 60, 30 )];
[[window contentView] addSubview:well];
[well release];
// ****** Date Picker ****** //
NSDatePicker *datePick = [[NSDatePicker alloc] initWithFrame:NSMakeRect( 120, _wndH - 145, 200, 24 )];
[[window contentView] addSubview:datePick];
[datePick release];
// ****** Level Indicator ***** //
NSLevelIndicator *level = [[NSLevelIndicator alloc] initWithFrame:NSMakeRect( 30, _wndH - 180, 200, 18 )];
[[window contentView] addSubview:level];
[[level cell] setLevelIndicatorStyle: NSContinuousCapacityLevelIndicatorStyle];
[level setMinValue:0];
[level setMaxValue:12];
[level setIntValue:6];
[level release];
/*
    NSRelevancyLevelIndicatorStyle, NSContinuousCapacityLevelIndicatorStyle,
    NSDiscreteCapacityLevelIndicatorStyle, NSRatingLevelIndicatorStyle
*/
// ***** Progress Indicator ***** //
NSProgressIndicator *progress = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect( 30, _wndH - 220, 200, 20 )];
[[window contentView] addSubview:progress];
[progress release];
// ****** Segmented Control ****** //
NSSegmentedControl *seg = [[NSSegmentedControl alloc] initWithFrame:NSMakeRect( 30, _wndH - 260, 120, 24 )];
[[window contentView] addSubview:seg];
[seg release];
[seg setSegmentCount:2];
[seg setLabel:@"First" forSegment:0];
[seg setLabel:@"Second" forSegment:1];
// ****** Arrw/ValueFld ****** //
NSStepper *arrw = [[NSStepper alloc] initWithFrame:NSMakeRect( 160, _wndH - 260, 22, 26 )];
[[window contentView] addSubview:arrw];
[arrw release];
[arrw setContinuous:YES];
[arrw setAutorepeat:YES];
[arrw setValueWraps:NO];
[arrw setMaxValue:100];
[arrw setMinValue:0];
[arrw setIntValue:60];
NSTextField *valueFld = [[NSTextField alloc] initWithFrame:NSMakeRect( 180, _wndH - 257, 50, 20 )];
[[window contentView] addSubview:valueFld];
[valueFld release];
[valueFld setAlignment:NSCenterTextAlignment];
[valueFld takeStringValueFrom:arrw];
// Make each target of the other
[arrw setTarget:valueFld];
[arrw setAction:@selector(takeIntValueFrom:)];
[valueFld setTarget:arrw];
[valueFld setAction:@selector(takeIntValueFrom:)];
// ***** NSTabView ******* //
   NSTabView *tab = [[NSTabView alloc] initWithFrame:NSMakeRect( 340, _wndH - 260, 280, 100 )];
   NSTabViewItem* item1=[[NSTabViewItem alloc] initWithIdentifier:@"1"];
   [item1 setLabel:@"One"];
   [tab addTabViewItem:item1];
   [item1 release];
   NSTabViewItem* item2=[[NSTabViewItem alloc] initWithIdentifier:@"2"];
   [item2 setLabel:@"Two"];
   [tab addTabViewItem:item2];
   [item2 release];
   NSTabViewItem* item3=[[NSTabViewItem alloc] initWithIdentifier:@"3"];
   [item3 setLabel:@"Three"];
   [tab addTabViewItem:item3];
   [item3 release];
   [[window contentView] addSubview:tab];
   [tab release];
// ***** NSMatrix ***** //
 int n;
 
 NSButtonCell *cell = [[NSButtonCell alloc]init];
 [cell setButtonType:NSRadioButton];
 // Width/height not critical if sizeToCells is used!
 id matrix = [[NSMatrix alloc] initWithFrame:NSMakeRect( 260, _wndH - 270, 100, 100 ) 
              mode:NSRadioModeMatrix 
            prototype:cell 
            numberOfRows:3 
            numberOfColumns:2];
 [matrix setCellSize:NSMakeSize( 34, 34 )];
 [matrix setIntercellSpacing: NSMakeSize( 3, 3 )];
 [matrix sizeToCells];
 NSArray *cellArray = [matrix cells];
 for ( n = 0; n <= 5; n++ )
 {
  [[cellArray objectAtIndex: n ] setTitle:[NSString stringWithFormat:@"%d", n+1] ];
  [[cellArray objectAtIndex: n ] setTag: n + 1 ];
 }
 [[window contentView] addSubview:matrix];
 [cell release];
 [matrix release];
// ***** NSButton Types ****** //
#define _top  _wndH - 320
#define _left   30
#define _cellW 190
#define _cellH 40
#define _vg 10   //vertical gutter
#define _hg  6
NSButton *btn[14];
NSInteger count, row, col;
NSRect btnR;
count = 1;
  for ( row = 0 ; row <= 4; row++ )
  {
    for ( col = 0; col <= 2; col++ )
    {
     if( row == 4 && col == 2 )  break;   //Creates unbalanced grid
     btnR = NSMakeRect( _left + (_cellW+_vg)*col, _top - (_cellH+_hg)*row, _cellW, _cellH );
     btn[count] = [[NSButton alloc]initWithFrame:btnR];
     [btn[count] setBezelStyle:count ];
     switch (count)
       {
        case 1: [btn[count] setTitle: @"NSRoundedBezelStyle" ]; break;
        case 2: [btn[count] setTitle: @"NSRegularSquareBezelStyle" ]; break;
        case 3: [btn[count] setTitle: @"NSThickSquareBezelStyle" ]; break;
        case 4: [btn[count] setTitle: @"NSThickerSquareBezelStyle" ]; break;
        case 5: [btn[count] setTitle: @"" ]; break;  // NSDisclosureBezelStyle
        case 6: [btn[count] setTitle: @"NSShadowlessSquareBezelStyle" ]; break;
        case 7: [btn[count] setTitle: @"" ]; break;  // NSCircularBezelStyle
        case 8: [btn[count] setTitle: @"NSTexturedSquareBezelStyle" ]; break;
        case 9: [btn[count] setTitle: @"" ]; break;  // NSHelpButtonBezelStyle
        case 10: [btn[count] setTitle: @"NSSmallSquareBezelStyle" ]; break;
        case 11: [btn[count] setTitle: @"NSTexturedRoundedBezelStyle" ]; break;
        case 12: [btn[count] setTitle: @"NSRoundRectBezelStyle" ]; break;
        case 13: [btn[count] setTitle: @"NSRecessedBezelStyle" ]; break;
        case 14: [btn[count] setTitle: @"" ]; break;  // NSRoundedDisclosureBezelStyle
        }
   [[window contentView] addSubview: btn[count]];
   [btn[count] release];
   count++;
   }
}
 [NSApp activateIgnoringOtherApps:YES];
 [NSApp run];
 [pool drain];
}
EndC
'----- end ------
Steve Van Voorst


To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: SVanVoorst <[email protected]>
Subject: Tutorial_4
Date: September 3, 2011 10:58:25 AM CDT

Sometimes you need to draw.  In Cocoa, this is done inside of an NSView using the -drawRect method as shown by this demo.  Normally we would have to list our methods inside of BeginCDeclaration...EndC, but in this case they are called automatically so this is not necessary.  The three methods called automatically for us are: -initWithFrame, -drawRect, and -isFlipped.  We could leave out -initWithFrame if we wanted to, but sometimes initializing data needs to be provided and this is where it would be stored.  I left it in for completeness, but the demo should run ok with it.  -drawRect is where all the action is and provides the drawing code.  I used calls for text and basic shapes from the NSBezierPath class.  These are similar to the calls used in Core Graphics.  It is also possible to create a CGContext inside -drawRect and use CG calls like we do in Carbon.  -isFlipped is important because it controls the location of the origin.  With Cocoa the origin is at the bottom left just like we learned in math class when we started creating graphs.  However, a lot of us got used to having the origin at the top left because that's where the early computers put it.  If you want to draw from the top down, then set -isFlipped to return YES.  If you want to draw from the bottom up, then set -isFlipped to return NO or omit the method.  By default Cocoa will draw from the bottom up if you don't tell it otherwise.  The next demo will show you how to print your masterpiece.

'------ start -----
BeginCDeclaration
@interface DrawView : NSView
//methods automatically called
@end  //interface
EndC
BeginCFunction
@implementation DrawView : NSView;
- (id)initWithFrame:(NSRect)frameRect
{
 if ((self = [super initWithFrame:frameRect]) != nil) 
 {
  self = [super initWithFrame:frameRect];
  // Add initialization code here
 }
 return self;
}
- (void)drawRect:(NSRect)rect
{
// ****** Background ***** //
[[NSColor whiteColor] set];
[NSBezierPath fillRect:rect];
// ****** Attributed text ****** //
NSString *myStr;
NSPoint myPt;
NSMutableDictionary *attr = [NSMutableDictionary dictionary];
[attr setObject:[NSFont fontWithName:@"Lucida Grande" size:18] forKey:NSFontAttributeName];
myStr = @"Attributed Text Drawn in an NSView";
myPt = NSMakePoint(30,20);
[myStr drawAtPoint:myPt withAttributes:attr];
[NSBezierPath setDefaultLineWidth:3.0];
// ****** Line ****** //
NSPoint begin, end;
begin = NSMakePoint( 30, 50 );
end = NSMakePoint( 360, 50 );
[NSBezierPath strokeLineFromPoint: begin toPoint:end];
// ***** Hashed Line ****** //
float lineDash[1];
NSBezierPath *hash = [NSBezierPath bezierPath];
[hash moveToPoint:NSMakePoint( 30, 70 )];
[hash lineToPoint:NSMakePoint( 360, 70 )];
lineDash[0] = 10;  //dash
lineDash[1] = 4;   //gap
[hash setLineDash:lineDash count: 2 phase:0.0 ];
[hash stroke];
// ****** Rounded Rectangle ****** //
NSRect  R = NSMakeRect(100, 100, 100, 100);
[[NSColor greenColor] set];
NSBezierPath *parr = [NSBezierPath bezierPath];
[parr appendBezierPathWithRoundedRect: R xRadius: 10.0 yRadius: 10.0 ];
[parr stroke];
// ****** Circle ****** // 
NSRect dotR = NSMakeRect( rect.size.width/2 - 50, rect.size.height/2 - 80, 100, 100 );
[[NSColor redColor] set]; 
[[NSBezierPath bezierPathWithOvalInRect:dotR] fill];
// ****** Oval ****** //
NSRect ovalR = NSMakeRect( 100, 230, 200, 100 );
[[NSColor magentaColor] set]; 
[[NSBezierPath bezierPathWithOvalInRect:ovalR] fill];
// ***** Polygon ****** //
[[NSColor blackColor] set]; 
NSBezierPath *path = [NSBezierPath bezierPath];
[path moveToPoint: NSMakePoint( 220.0, 150.0 )];
[path lineToPoint: NSMakePoint( 245.0, 175.0 )];
[path lineToPoint: NSMakePoint( 270.0, 150.0 )];
[path lineToPoint: NSMakePoint( 295.0, 150.0 )];
[path lineToPoint: NSMakePoint( 250.0, 120.0 )];
[path lineToPoint: NSMakePoint( 220.0, 150.0 )];
[path closePath];
[path setLineJoinStyle: NSRoundLineJoinStyle];
[path stroke];
NSRect outer = NSMakeRect( 80, 310, 100, 50 );
NSRect inner = NSInsetRect( outer, 1, 1 );
// ****** Filled Rectangle ***** //
[[NSColor blueColor] set];
[NSBezierPath fillRect:inner];
// ****** Stroked Rectangle ****** //
[[NSColor grayColor] set];
[NSBezierPath strokeRect:outer];
// ******Arc ******* //
[[NSColor blackColor] set]; 
NSBezierPath *arc = [NSBezierPath bezierPath];
[arc moveToPoint:NSMakePoint( 200, 320 )];
[arc appendBezierPathWithArcFromPoint:NSMakePoint( 200, 380 ) toPoint:NSMakePoint( 260, 380 ) radius:60];
[arc stroke];
}
// ----- Use this if you want 0,0 (origin) to be top, left ---- //
// ----- Otherwise origin will be at bottom, left (Unflipped) ----- //
-(BOOL)isFlipped
{
 return YES;
}
@end //implementation
EndC
BeginCCode
{
 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; 
 [NSApplication sharedApplication];
 [NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
// ----- Menubar and Menu ---- //
    id menubar = [[NSMenu new] autorelease];
    id appMenuItem = [[NSMenuItem new] autorelease];
    [menubar addItem:appMenuItem];
    [NSApp setMainMenu:menubar];
    id appMenu = [[NSMenu new] autorelease];
    id quitMenuItem = [[[NSMenuItem alloc] initWithTitle:@"Quit"
        action:@selector(terminate:) keyEquivalent:@"q"] autorelease];
    [appMenu addItem:quitMenuItem];
    [appMenuItem setSubmenu:appMenu];
//----- Window ---- //
   #define _wndW  440
   #define _wndH  500
   id window = [ [ NSWindow alloc ] 
                       initWithContentRect:NSMakeRect( 0, 0, _wndW, _wndH )
                       styleMask: NSClosableWindowMask | NSTitledWindowMask
                       backing:NSBackingStoreBuffered
                       defer:NO];
  [window center];
  [window setTitle: @"NSView_demo" ];
  [window makeKeyAndOrderFront:nil]; 
// ------- Create an instance of DrawView (NSView) ------ //
 id myDrawView = [[DrawView alloc]initWithFrame:NSMakeRect( 20, 20, _wndW - 40, _wndH - 40 )];
 [[window contentView] addSubview:myDrawView];
 [myDrawView release];
[NSApp activateIgnoringOtherApps:YES];
[NSApp run];
[pool drain];
}
EndC

'----- end ------

Steve Van Voorst


To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

From: Brian S <[email protected]>
Subject: Re: [FB] FBCocoaTutorial
Date: September 3, 2011 11:24:38 PM CDT

On Sep 3, 2011, at 6:12 PM, Edwards, Waverly wrote:


I believe "new" and [[ object alloc] init] are equivalent.
If you do not have a custom allocator then you are using the the default allocator.
"new" just performs the same allocation and initializing job.  Its just shorter.

Also, it is possible a given implementation might need a custom initialization for object. In that case you would want to call it with [[obj alloc] init] to pick up the instance method that does the custom init. The default initialization from the class method ( i.e. '+new' from NSObject) might not be what is desired even though sufficient for most needs.

Brian S



To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]


Rich Love - Carnation Software

Get 'Say it & Mail it' for iPhone

http://www.SayitMailit.com


MacWise Terminal emulation for Macintosh

http://www.CarnationSoftware.com

Twitter - http://twitter.com/CarnationSW

Email - [email protected]

512 858-9234
















To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]